Search code examples
c#entity-framework-coreautofac

How to register DbContextPool using Autofac?


Microsoft's DI has AddDbContextPool but how to do it with Autofac?


Solution

  • So, I guess, the standard workaround for cases like "How to register something that exists in Microsoft's DI (logging, DbContext, etc.)?" is using ServiceCollection and then calling Populate method.

    My realization for DbContextPool:

    public static void RegisterDbContextPool<T>(this ContainerBuilder builder, Action<DbContextOptionsBuilder> options) where T : DbContext {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddDbContextPool<T>(options);
        builder.Populate(serviceCollection);
    }
    

    Docs