4

I create entity framework db context in startup

 services.AddTransient<MyContext>(_ => new MyContext(connectionString));

I inject this context in every service class where I need entity framework to add/edit/delete or what ever.

private readonly MyContext context;

public ArchiveService(MyContext context)
{
    this.context = context;
}

For IoC i am using Microsoft.Extensions.DependencyInjection. This mean that my dependency injection container is responsible to dispose db context.

How can I be sure that context is disposed?

Do I need to configure something to dispose db context?

Thank you for help.

Raskolnikov
  • 3,791
  • 9
  • 43
  • 88
  • see this: [lifespan/scope of context in a winform application](http://stackoverflow.com/questions/5663754/entity-framework-4-lifespan-scope-of-context-in-a-winform-application) – Vikrant Nov 15 '16 at 09:25

1 Answers1

5

In asp.net core, all services which you registered with AddTransient are disposed together with a scope, so - when request ends. What's the difference between Transient and Scoped then you might ask? For Transient - new instance is created for every resolution. In your case - all your service classes will have distinct instances of MyContext. All of them will be disposed when request ends. For Scoped - only one instance will be created for given request (scope), so all your services would have shared the same instance, which is disposed when request ends.

Evk
  • 98,527
  • 8
  • 141
  • 191