注入的WebAPI的AccountController我有默認constuctor和構造函數使用參數喜歡這裏:如何的WebAPI
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文章blog但他們不說話怎麼如果我起飛參數的構造函數,我得到一個錯誤解決這種情況與構造havaving PARAMS 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,我是沒有得到注入,以及:基於@IgorPashchuk suggeston現在MyController
是越來越現在注入
public class MyController : ApiController
{
[Dependency]
public IRepository Repository { get; set; }
public IHttpActionResult Get()
{
var test = Repository.GetSomething(); // Repository is null here always
}
}
更新1。 但AccoutController不是。我刪除了默認的構造函數,但仍然出現錯誤。
更新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>
類型。我發表了關於此問題的另一個問題How to construct ISecureDataFormat<AuthenticationTicket> with unity
'ApplicationUserManager'存在:'.RegisterType()' –
sreginogemoh
我需要'Unity.Mvc'包嗎?這是接縫,就像我不再需要那樣? – sreginogemoh
@sreginogemoh,你是對的。對不起,我錯過了。你的第二個問題的答案是:這取決於。你不需要它來達到這個目的。但是,您肯定需要創建自定義依賴項解析器,因爲Web API不知道您的Unity容器。 –