Reputation: 3999
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.
Upvotes: 4
Views: 2362
Reputation: 101533
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.
Upvotes: 5