Search code examples
asp.netdependency-injectionasp.net-web-api2autofacasp.net-identity-2

Injecting ISecureDataFormat in Web API 2 AccountController using Autofac


I am using ASP.NET Identity 2.2 in a Web API 2 project but I am unsure how to wire up the ISecureDataFormat<AuthenticationTicket> dependency of the AccountController using Autofac.

I tried this:

builder.RegisterType<ISecureDataFormat<AuthenticationTicket>>()
       .As<TicketDataFo‌​rmat>(); 

and getting error:

The type 'Microsoft.Owin.Security.ISecureDataFormat`1[Microsoft.Owin.Security.Authenticat‌​ionTicket]' is not assignable to service 'Microsoft.Owin.Security.DataHandler.TicketDataFormat'

None of the questions I came across seem to work using the latest stable release of ASP.NET Identity.

Any help is greatly appreciated.


Solution

  • You have to do the oposite. With Autofac you register a type as a Service.

    builder.RegisterType<TicketDataFo‌​rmat>()
           .As<ISecureDataFormat<AuthenticationTicket>>(); 
    

    and based on this answer, it seems that you also need to register a IDataSerializer<AuthenticationTicket> and a IDataProtector implementation.

    builder.RegisterType<TicketSerializer>()
           .As<IDataSerializer<AuthenticationTicket>>();
    builder.Register(c => new DpapiDataProtectionProvider().Create("ASP.NET Identity"))
           .As<IDataProtector>();