Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 533
Geremias Reyero Avatar asked Nov 28 '18 22:11

Geremias Reyero


People also ask

Do you need to dispose of DbContext?

Calling the Dispose method ensures that your Connection is closed. So, as long as you let DbContext manage your connections, feel free to ignore the Dispose method.

Which method is used to let the DbContext know an entity should be deleted?

Remove(Object) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.

How does DbContext work in .NET Core?

A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns. Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.


1 Answers

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.

like image 177
John-Luke Laue Avatar answered Sep 23 '22 00:09

John-Luke Laue