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

Multiple controller constructors when injecting dependencies using Unity.Mvc5

我是依赖注入的新手,我刚刚设置了 Unity.Mvc5 并取得了一些成功。但是现在我面临着我的控制器中有多个构造函数的问题class。我已经有了处理我的 UserManager 的构造函数,按照教程我明白我需要另一个构造函数来实例化我的接口。但是,当我这样做时,出现以下错误:

The type OrganisationController has multiple constructors of length 1. Unable to disambiguate.

来自我的控制器的片段:

    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 我有另一个构造函数用于实现接口。

使用 DI 时,构造函数具体是 for DI。没有理由创建备用构造函数(尤其是在控制器上,因为唯一的调用者是 ControllerFactory,它将调用委托给 DI 容器)。

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

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

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

您是否尝试过 InjectionConstructor 属性?

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