![](/img/trans.png)
[英]How can I merge ASP .NET Identity/ Identity Framework DbContext class to my DbContext class which is on another Assembly/ Project
[英]How can I configure Ninject to inject my DbContext for use with ASP.NET Identity Framework?
我想使用Ninject注入我的DbContext ASP.NET身份框架。
目前,我的web.config
文件中包含以下行:
<appSettings>
<add key="owin:appStartup" value="OwinTest.Identity.OwinStart, OwinTest.Identity" />
</appSettings>
这将导致在我的OwinTest.Identity项目中的类OwinStart
上OwinStart
Configuration()
方法。
这是我的OwinStart课程:
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();
}
}
如您所见,当我真的想使用Ninject注入DbContext时,我使用new
关键字创建了DbContext
的实例。
我是否可以将Ninject连接起来以在OWIN中注入数据库上下文?
我猜您在这里能做的最好的事情是:
DependencyResolver.Current.GetService<IMyContext>();
更新
在讨论聊天中的问题后,我们确定:
这基本上意味着DI容器不能在两者之间共享。 应用程序的合成根应尽可能接近起点,对于OWIN而言,这意味着启动方法。
在这个特殊的用例中,当您在合成根目录旁边实例化DbContext时,在该应用程序中进行ninject不会带来任何好处。
链接的文章Trailmax说:
同样,这不使用我们的Unity容器,而是使用Owin进行对象解析。 由于多种原因,我们不想将Owin注册与Unity注册混在一起(最大的原因是两个容器之间缺乏生命周期管理)。
因此,将DI容器与owin一起使用的主要优点是,如果您已经在其余的应用程序中使用它,并且希望owin和其余的应用程序共享注册。 那不是你的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.