使用Unity.Mvc5注入依赖项时的多个控制器构造函数

时间:2016-03-17 13:18:26

标签: c# asp.net asp.net-mvc dependency-injection unity-container

我对依赖注入非常陌生,我只是设置了Unity.Mvc5,并且取得了一些成功。但是现在我遇到了控制器类中多个构造函数的问题。我已经有了处理我的UserManager的构造函数和以下教程我明白我需要另一个构造函数来实例化我的接口。但是,当我这样做时,我收到以下错误:

  

OrganisationController类型有多个长度为1的构造函数。无法消除歧义。

来自我的控制器的片段:

    private IPush _pushMessage;

    // Here is the problem!
    public OrganisationController(IPush pushMessage)
    {
        _pushMessage = pushMessage;
    }

    public OrganisationController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {
    }

    public OrganisationController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
        var provider = new DpapiDataProtectionProvider("MyApp");
        UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("PasswordReset"));
    }

    public UserManager<ApplicationUser> UserManager { get; private set; }

我的UnityConfig.cs如下:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        container.RegisterType<IPush, PushMessage>();
        container.RegisterType<IController, OrganisationController>();
        container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>();
        container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }
}

我不知道如何告诉Unity我有另一个构造函数用于实现接口。

2 个答案:

答案 0 :(得分:5)

使用DI时,构造函数专门用于 DI。没有理由创建备用构造函数(特别是在控制器上,因为唯一的调用者是ControllerFactory,它将调用委托给DI容器。)

事实上,using multiple constructors with dependency injection is anti-pattern应该避免。

相关:Rebuttal: Constructor over-injection anti-pattern

答案 1 :(得分:1)

虽然我同意@ NightOwl888的其他答案。在某些情况下,您可能希望拥有多个构造函数。

您是否尝试过InjectionConstructor属性?

[InjectionConstructor]
public OrganisationController(IPush pushMessage)
{
    _pushMessage = pushMessage;
}