简体   繁体   中英

How to get instance of DbContext in ASP.NET Core 2.0 where I want?

How to get instance of DbContext in ASP.NET Core 2.0 where I want? To connect DataBase I used services

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

This is described in the documentation :

Excerpt:

EF Core supports using DbContext with a dependency injection container. Your DbContext type can be added to the service container by using the AddDbContext method.

AddDbContext will make both your DbContext type, TContext, and the corresponding DbContextOptions available for injection from the service container.

Application code (in ASP.NET Core):

public class MyController
{
  private readonly BloggingContext _context;

  public MyController(BloggingContext context)
  {
    _context = context;
  }

  ...
}

Application code (using ServiceProvider directly, less common):

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

var options = serviceProvider.GetService<DbContextOptions<BloggingContext>>();
public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Your application can now pass the DbContextOptions when instantiating a context, as follows:

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM