How to get a instance of DbContext from pool with dependency injection during method?

Viewed 1025

I want to have DbContext in a function from the pool during a using scope

I already tried to add IServiceProvider to the factory and let the factory resolve the context and put it into a UoW but then it tells me the same contains is used in other threads.

services.AddDbContextPool<EmployeeContext>(options => options.UseSqlServer(connection));
...
using (var unitOfWork = factory.CreateUnitOfWork())
{
}

I want to create a unit-of-work scope within a function which is using the DbContextPool of dependency injection.

1 Answers

You can create a scope inside your method but first you have to inject IServiceScopeFactory to your class.

using Microsoft.Extensions.DependencyInjection;


public class SomeService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public SomeService(IServiceScopeFactory serviceScopeFactory)
    {
        _serviceScopeFactory = serviceScopeFactory;
    }

    public Task DoStuff()
    {
        using (var serviceScope = _serviceScopeFactory.CreateScope())
        {
            var unitOfWork =  serviceScope.ServiceProvider.GetRequiredService<UnitOfWork>();
        }
    }
}

Keep in mind that the object you created will be disposed when you dispose the scope. Also, if you don't dispose the scope, you will get memory leaks

Related