如何使用unity构造ISecureDataFormat <authenticationticket>

时间:2015-09-07 20:22:17

标签: dependency-injection unity-container asp.net-web-api2

我的webapi帐户控制器上有一个consturctor,如下所示:

public AccountController(ApplicationUserManager userManager, ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
   _userManager = userManager;
   AccessTokenFormat = accessTokenFormat;
}

但是Unity无法构造ISecureDataFormat<AuthenticationTicket>,因为构造函数不起作用,直到我取消第二个参数。

public AccountController(ApplicationUserManager userManager)
{
   _userManager = userManager;
}

如何使用Unity构建第二个参数? 我的Unityconfig:

.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>();

1 个答案:

答案 0 :(得分:0)

您尚未在IDataProvider内注册UnityContainer类型 (我不知道为什么你在你的Unity配置中注释掉了)但是SecureDataFormat<AuthenticationTicket>构造函数需要它。

public class SecureDataFormat<TData> : ISecureDataFormat<TData>
{
    public SecureDataFormat(IDataSerializer<TData> serializer, IDataProtector protector, ITextEncoder encoder)

我也面临同样的问题。以下统一配置为我解决了问题

container.RegisterType<ITextEncoder, Base64UrlTextEncoder>();
container.RegisterType<IDataSerializer<AuthenticationTicket>, TicketSerializer>();
container.RegisterInstance(new DpapiDataProtectionProvider().Create("ASP.NET Identity"));
container.RegisterType<ISecureDataFormat<AuthenticationTicket>, SecureDataFormat<AuthenticationTicket>>();