2

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.

Josjr87
  • 193
  • 1
  • 13

1 Answers1

3

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

Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • Thanks.. based on this I did find more info also on https://stackoverflow.com/questions/50200200/net-core-iservicescopefactory-createscope-vs-iserviceprovider-createscope-e – Josjr87 Jun 21 '19 at 19:27
  • Thanks! This saved a ton of time in research :) – Robert Sep 03 '21 at 21:24