我是依赖注入(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并且应该避免。
关于c# - 使用 Unity.Mvc5 注入(inject)依赖项时的多个 Controller 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36061730/