Help with injection, please

May 13, 2010 at 6:46 AM

Yikes, that doesn't sound too good!

I was hoping someone could please help me with this;


I want to include some additional parameters on a view's constructor, like this;

        public LoginView(IEventAggregator eventAggregator, string test)
            this._eventAggregator = eventAggregator;
            this._test = test;


It's the "test" bit I can't seem to pass/inject correctly.

Another View loads this view like this;


var pageLogin = Container.Resolve<MainContentModule.Views.LoginView>();


Who do I inject this string during the construction of the view?




May 14, 2010 at 3:03 PM


When you do constructor injection, the container will try to find the type you’ve specified (string in your case) to inject it into the object you are resolving (the LoginView in your case). If you haven’t registered that type or an instance of that type into the container, it will try to instantiate it. Since the constructors for string contain parameters that the container can’t resolve, it will throw an exception. So in order to inject a dependency that the container can’t construct into an object, you must already have that dependency registered.

In this case you could register a named instance of your type through the IUnityContainer.RegisterInstance<T> method.

The code for registering it would look like this:

container.RegisterInstance<string>("MyString", "Test");

And the LoginView constructor would look like this:

public LoginView(IEventAggregator eventAggregator, [Dependency("MyString")]string test) 
    this._eventAggregator = eventAggregator; 
    this._test = test; 

You can find more information about it in this article.

However, if what you are trying to pass to the LoginView is only a string, construction injection might be a bit of an overkill. Dependency injection is generally useful to decouple a class from the concrete implementation of its dependencies, and to improve testability (among other things).In this case, the implementation of string won’t change, and you can easily mock it in a test. So if you’re going to pass a simple type (string, int, etc), I would recommend you to follow a simpler approach, for example defining ‘test’ as a property, and setting its value directly.

If you have another questions realted specifically to Unity, you could ask it in the Unity Forums where you could get a more specific answer, as the community there deals specifically with Unity.

Please let me know if this helps.

Damian Schenkelman