Reputation: 23680
I'd like to use Ninject to inject my DbContext ASP.NET Identity Framework.
At the moment I have the following line in my web.config
file:
<appSettings>
<add key="owin:appStartup" value="OwinTest.Identity.OwinStart, OwinTest.Identity" />
</appSettings>
This causes the Configuration()
method on class OwinStart
in my OwinTest.Identity project to be called.
Here's my OwinStart class:
public class OwinStart
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext<IMyContext>(this.GetDbContext);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(
new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login")
});
}
/// <summary>
/// Gets an instance of the DbContext for OWIN
/// </summary>
/// <returns></returns>
private IMyContext GetDbContext()
{
// Create dbcontext instance
return new MyContext();
}
}
As you can see, I create an instance of my DbContext
using the new
keyword, when I really want to be making use of Ninject to inject my DbContext in.
Is it possible for me to wire up Ninject to inject my database context in within OWIN?
Upvotes: 0
Views: 996
Reputation: 26290
I'm guessing the best you can do here is:
DependencyResolver.Current.GetService<IMyContext>();
Update
After discussion the issue in chat we established that:
This basically means that DI container can't be shared between the two. The composition root of an application should be as close to the starting point as possible, which, for OWIN, means the start up method.
In this particular use case you are not gaining anything from having ninject in this application as you are instantiating your DbContext right next to your composition root.
The article trailmax linked says:
Also this does not use our Unity container, this uses Owin for object resolution. We don’t want to mix Owin registrations with Unity registrations for many reasons (the biggest reason is lack of lifetime management between 2 containers).
So the main advantage of using a DI container with owin would be if you are already using it for the rest of the application, and want owin and the rest of the application share the registrations. That's not your case.
Upvotes: 1