我有默认的构造器和构造函数,参数如下所示:
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>();但问题是默认构造函数总是被调用。我阅读了taht的文章博客,但他们并没有讨论如何用构造函数来解决这种情况,并没有使用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
}
}基于@IgorPashchuk的更新1建议现在MyController正在被注入。但AccoutController不是。我被删除了默认的构造函数,但仍然得到了错误。
UPDATE 2我通过取出第二个param来修改构造函数:
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>类型。我发布了关于这个问题的另一个问题,团结一致
发布于 2015-09-07 19:00:04
应该删除无参数构造函数。
接下来,您需要配置一个自定义依赖解析器,它将基本包装您的联合容器。请参阅http://www.asp.net/web-api/overview/advanced/dependency-injection
在此之后,确保您注册了所有类型。例如,我没有看到ApplicationUserManager的注册。您正在注册UserManager<ApplicationUser, int>,而不是ApplicationUserManager,这是IoC容器将试图解决的问题。
https://stackoverflow.com/questions/32444534
复制相似问题