Reputation: 1136
In an attempt to use Ninject with a new Web API 2 project that uses ASP.NET Identity I have come across some odd behavior. I can't get the callbacks passed to CreatePerOwinContext() to fire for requests to Web API controllers. For MVC controllers they work fine.
Steps to recreate:
I'm not a ninject aficionado so I'm unsure if it's something I am doing wrong or a bug in the Ninject OWIN extensions. I'm leaning towards leaving the OwinContext behind and simply using Ninject perHttpRequest scoping but I'm unsure if the ASP.NET Identity system will break. I've heard there may be internal calls to OwinContext.Get() that would break if I didn't keep things in the OWIN context.
Much appreciate anyone's thoughts.
Upvotes: 2
Views: 1523
Reputation: 1136
I ended up getting around this by using Ninject for all lifetime management. Evidently .CreatePerOwinContext() is a stop gap solution that you don't need if using a full blown DI tool.
The only thing I've seen to be aware of is that for cookie based auth, ASP.NET Identity will look in OwinContext for its UserManager. I am using token based auth but I have seen some folks go ahead and stuff a UserManager into the OwinContext.
My Ninject bindings:
private static readonly Lazy<IKernel> _lazyKernel = new Lazy<IKernel>(CreateKernel);
// Access the singleton kernel via this property
public static IKernel Kernel { get { return _lazyKernel.Value; } }
private void ConfigureNinject(IAppBuilder app)
{
app.UseNinjectMiddleware(() => Kernel);
Kernel.Bind<IAppBuilder>().ToConstant(app);
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<AuthDbContext>().ToSelf().InRequestScope().WithConstructorArgument("connectionString", "MyConnectionString");
kernel.Bind<IUserStore<MyApplicationUser, int>>().To<MyUserStore>().InRequestScope();
kernel.Bind<IRoleStore<MyRole, int>>().To<MyRoleStore>().InRequestScope();
kernel.Bind<MyUserManager>().ToSelf().InRequestScope();
kernel.Bind<ISecureDataFormat<AuthenticationTicket>>().To<SecureDataFormat<AuthenticationTicket>>();
kernel.Bind<IDataSerializer<AuthenticationTicket>>().To<TicketSerializer>();
kernel.Bind<IDataProtector>().ToMethod(x => x.Kernel.Get<IAppBuilder>().GetDataProtectionProvider().Create("ASP.NET Identity"));
kernel.Bind<ITextEncoder>().To<Base64UrlTextEncoder>();
}
Upvotes: 3