简体   繁体   中英

When dispose a dbcontext in .net core?

im making a project with a persistence layer, domain layer, and business layer, i implementing the generic repository pattern and unit of work with entity framework core.

I want to use this project in a web api rest and in a UWP project.

The correct ways its override the method?, add the context in the startup configureservices? When dispose a dbcontext?

Read documentation on configuring DbContext: https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

Basically, you add it to your services:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Then you inject it into whatever class you want. An easy example would be inejecting it into a Controller (but you could inject into any class that is added to your services):

public class MyController
{
    private readonly BloggingContext _context;

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

    ...
}

The Dependency Injection library will then handle disposal - you do not call Dispose directly. This is described in documentation here .

The framework takes on the responsibility of creating an instance of the dependency and disposing of it when it's no longer needed.

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