使用注入的 DbContext 以及在 Startup.Auth 中创建的 DbContext

Using injected DbContext along with DbContext created in Startup.Auth

在Asp.Net MVC中,默认模板自带Startup class在Startup.Auth.cs

public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

根据此模板中的注释,每个请求都会创建一个 ApplicationDbContext 的实例。

在我的应用程序中,我使用存储库模式并将 ApplicationDbContext 注入到存储库中。在我的例子中,我使用 Ninject,如果需要,它可以在多个存储库之间共享相同的上下文。

有没有办法在Startup.Auth中使用相同的注入ApplicationDbContext?不太确定更改默认模板是否是个好主意,同时我们在 1 个请求中创建了相同上下文的 2 个实例...

在我的 Ninject 代码中,我将 ApplicationDbContext 绑定到自身,如下所示:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();

不确定将上下文绑定到自身而不是创建接口是否是一种不好的做法? (虽然它工作正常)。

Not really sure if this a bad practice to bind the context to itself instead of creating an interface?

DbContext 注册为自身和每个请求的生命周期是很正常的。

个人 喜欢实现 IDbContext 接口,这样当我对存储库进行单元测试时模拟会更清晰。所以,my repositories 依赖于抽象而不是具体的实现。

public class ApplicationDbContext : DbContext, IDbContext
{
}

IDbContext

public interface IDbContext
{
   DbSet<MyEntity> MyEntities { get; set; }
   ...
}