Raskolnikov Raskolnikov - 1 year ago 199
C# Question

How to dispose dbcontext in container?

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.

Evk Evk
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download