Dependency injection in MVC 3 using a single structure

I implemented dependency injection in MVC 3 framework and following the instructions.

This worked, but I have a few questions regarding this:

Here is my implementation:

public interface ID { string MReturn(); } 

And the classes implementing this interface:

 public class D:ID { public string MReturn() { return "Hi"; } } public class E : ID { public string MReturn() { return "HiE"; } } public class F : ID { public string MReturn() { return "Hif"; } } 

In bootstrapper class

  private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<ID, D>(); container.RegisterType<IController, HomeController>("feedbackRepo"); container.RegisterType<ID, E>(); container.RegisterType<ID, F>(); // register all your components with the container here // it is NOT necessary to register your controllers // eg container.RegisterType<ITestService, TestService>(); return container; } 

Now my question

"I want to set the class of service D in the constructor of the Homecontroller, but according to the code above, it sets" class F "in the constructor.

Is there any way to do this? Any modification of the above code?

+6
source share
1 answer

The reason F is entered is the last registered implementation of the ID . It basically overwrites previous registrations.

If you have different implementations of an interface / base class, and you want to implement certain implementations in different controllers, you can register them as named instances:

 container.RegisterType<ID, D>("d"); container.RegisterType<ID, E>("e"); container.RegisterType<ID, F>("f"); 

and then register the controller in the container and enter the desired named instance of ID :

 container.RegisterType<HomeController>( new PerRequestLifetimeManager(), new InjectionConstructor(new ResolvedParameter<ID>("d")) ); 

Note that the controller is registered with the PerRequestLifetimeManager to ensure that new instances are created for each HTTP request.

+5
source

All Articles