c# - 使用 Unity.Mvc5 注入(inject)依赖项时的多个 Controller 构造函数

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

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

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

来 self 的 Controller 的片段:

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

最佳答案

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

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

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

关于c# - 使用 Unity.Mvc5 注入(inject)依赖项时的多个 Controller 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36061730/

相关文章:

c# - 来自类结构的类使用细节

c# - 使用 Xmlnclude 后如何删除不需要的属性?

c# - 如何在 Visual Studio MVC 项目中使用 application Insights REST API

asp.net - ArrayList 元素比较

mysql - 连接字符串错误。无法找到请求的 .Net Framework 数据提供程序

c# - View 显示不同的值,然后在其模型中显示不同的值

c# - HttpClient JsonReaderException 解析值时出现意外字符

c# - 为什么我的 LINQ 查询给我的是旧数据?

java - 在Android上将视频分成几部分

c# - Microsoft ASP.NET Web Pages 2 Data Nuget 包有什么用?