使用统一框架在MVC 3中进行依赖注入

use*_*881 6 .net c# asp.net-mvc dependency-injection asp.net-mvc-3

我已经在MVC 3统一框架中实现了依赖注入并遵循了指令.

它有效,但我有几个问题:

这是我的实现:

public interface ID
{

    string MReturn();
}
Run Code Online (Sandbox Code Playgroud)

实现此接口的类是:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

在bootstrapper类中,

    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;
    }
Run Code Online (Sandbox Code Playgroud)

现在我的问题是

"我想在Homecontroller构造函数中设置服务类D,但根据上面的代码,它在构造函数中设置了"class F".

有没有办法做到这一点?对上述代码的任何修改?

Dar*_*rov 5

F注入的原因是因为它是最后注册的实现ID.它基本上覆盖了以前的注册.

如果你有一些接口/基类的不同实现,并且你想在不同的控制器中注入特定的实现,你可以将它们注册为命名实例:

container.RegisterType<ID, D>("d");
container.RegisterType<ID, E>("e");
container.RegisterType<ID, F>("f");
Run Code Online (Sandbox Code Playgroud)

然后在容器中注册控制器并注入所需的命名实例ID:

container.RegisterType<HomeController>(
    new PerRequestLifetimeManager(),
    new InjectionConstructor(new ResolvedParameter<ID>("d"))
);
Run Code Online (Sandbox Code Playgroud)

请注意,注册控制器PerRequestLifetimeManager以确保为每个HTTP请求创建新实例.