【发布时间】:2015-09-07 18:50:39
【问题描述】:
我有默认构造函数和带有参数的构造函数,如下所示:
public class AccountController : ApiController
{
private const string LocalLoginProvider = "Local";
private ApplicationUserManager _userManager;
public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }
[Dependency]
public IRepository Repository{ get; private set; }
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
_userManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
}
我的统一配置在这里:
.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager())
.RegisterType<UserManager<ApplicationUser, int>, ApplicationUserManager>()
.RegisterType<ApplicationDbContext>(new HierarchicalLifetimeManager())
.RegisterType<ApplicationUserManager>()
.RegisterType<ISecureDataFormat<AuthenticationTicket>, SecureDataFormat<AuthenticationTicket>>()
.RegisterType<ITextEncoder, Base64UrlTextEncoder>()
.RegisterType<IDataSerializer<AuthenticationTicket>, TicketSerializer>()
//.RegisterType<IDataProtector>(() => new DpapiDataProtectionProvider().Create("ASP.NET Identity"))
.RegisterType<IUserStore<ApplicationUser, int>, CustomUserStore>(new InjectionConstructor(typeof(ApplicationDbContext)))
.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication))
.RegisterType<IOwinContext>(new InjectionFactory(o => HttpContext.Current.GetOwinContext()))
.RegisterType<IRepository, Repository>();
但问题是默认构造函数总是被调用。
我读了一篇文章blog,但他们没有谈论如何使用具有参数AccountController(ApplicationUserManager userManager, ISecureDataFormat<AuthenticationTicket> accessTokenFormat)的构造函数来解决这种情况@
如果我要取消无参数构造函数,我会收到错误消息:"An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.",
有没有人可以帮忙?
我也只有普通的 ApiController,我也没有被注入:
public class MyController : ApiController
{
[Dependency]
public IRepository Repository { get; set; }
public IHttpActionResult Get()
{
var test = Repository.GetSomething(); // Repository is null here always
}
}
更新 1 基于 @IgorPashchuk 建议现在 MyController 正在被注入。
但 AcoutController 不是。我删除了默认构造函数,但仍然收到错误。
更新 2 我通过取出第二个参数来更改带有参数的构造函数:
public class AccountController : ApiController
{
private const string LocalLoginProvider = "Local";
private ApplicationUserManager _userManager;
[Dependency]
public IRepository Repository{ get; private set; }
public AccountController(ApplicationUserManager userManager)
{
_userManager = userManager;
}
}
所以这样我得到的东西正在工作。我是否理解这意味着 Unity 无法构造类型 ISecureDataFormat<AuthenticationTicket>。我发布了另一个关于这个问题的问题How to construct ISecureDataFormat<AuthenticationTicket> with unity
【问题讨论】:
标签: dependency-injection unity-container asp.net-web-api2