Alex Sofin
Alex Sofin

Reputation: 137

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));

Upvotes: 5

Views: 13509

Answers (2)

Ehsan Gondal
Ehsan Gondal

Reputation: 375

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
}

Upvotes: 3

Erik Philips
Erik Philips

Reputation: 54638

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>>();

Upvotes: 5

Related Questions