7
votes

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?

1
When the controller is being disposed, call dispose on your repository and that should dispose the context. If you are using a service layer and not talking to the repository directly from the controller, then call dispose on the service which will call dispose on repo which will dispose the context.CodingYoshi
If you are using EF, you do not need unit of work because EF already works that way. Search for this online.CodingYoshi

1 Answers

25
votes

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.