How to construct ISecureDataFormat

2019-08-06 19:17发布

问题:

I have consturctor on my webapi account controller looking like that:

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

But Unity is not able to consruct the ISecureDataFormat<AuthenticationTicket>because the constructor is not working untill I taking off the second param.

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

How I can construct the second param with Unity? My 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:

You haven't registered type IDataProvider within UnityContainer (I don't knows why you comment out that within your unity config) however SecureDataFormat<AuthenticationTicket> constructor requires that.

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

I was also facing the same issue. Following unity config resolved issue for me

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