6

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

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

Here is my implementation :

public interface ID
{

    string MReturn();
}

And the classes which implement this interface are:

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 the 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

        // e.g. container.RegisterType<ITestService, TestService>();            

        return container;
    }

Now my question is

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

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

1 Answer 1

5

The reason why F is injected is because it is the last registered implementation of ID. It basically overwrites the previous registrations.

If you have different implementations of some interface/base class and you want to inject specific implementations in different controllers you could 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 inject the desired named instance of ID:

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.