【问题标题】:How to get instance of DbContext in ASP.NET Core 2.0 where I want?如何在我想要的 ASP.NET Core 2.0 中获取 DbContext 的实例?
【发布时间】:2019-09-30 15:37:03
【问题描述】:

如何在我想要的 ASP.NET Core 2.0 中获取 DbContext 的实例? 为了连接数据库,我使用了服务

string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MobileContext>(options => options.UseSqlServer(connection));

【问题讨论】:

    标签: c# entity-framework asp.net-core dependency-injection


    【解决方案1】:

    这在documentation中有描述:

    摘录:

    EF Core 支持将 DbContext 与依赖注入容器一起使用。可以使用 AddDbContext 方法将您的 DbContext 类型添加到服务容器中。

    AddDbContext 将使您的 DbContext 类型、TContext 和相应的 DbContextOptions 都可用于从服务容器注入。

    应用程序代码(在 ASP.NET Core 中):

    public class MyController
    {
      private readonly BloggingContext _context;
    
      public MyController(BloggingContext context)
      {
        _context = context;
      }
    
      ...
    }
    

    应用代码(直接使用ServiceProvider,不太常见):

    using (var context = serviceProvider.GetService<BloggingContext>())
    {
      // do stuff
    }
    
    var options = serviceProvider.GetService<DbContextOptions<BloggingContext>>();
    

    【讨论】:

    • 您应该在您的服务定位器示例代码中创建一个范围,因为上下文将被限定并且不能直接从注入的服务提供者中检索。
    【解决方案2】:
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }
    
        public DbSet<Blog> Blogs { get; set; }
    }
    

    您的应用程序现在可以在实例化上下文时传递 DbContextOptions,如下所示:

    var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
    optionsBuilder.UseSqlite("Data Source=blog.db");
    
    using (var context = new BloggingContext(optionsBuilder.Options))
    {
      // do stuff
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 2018-06-09
      • 2017-05-16
      • 1970-01-01
      • 2019-05-11
      • 2018-11-20
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多