mehdime / DbContextScope

A simple and flexible way to manage your Entity Framework DbContext instances
http://mehdi.me/ambient-dbcontext-in-ef6/
MIT License
631 stars 273 forks source link

Support of ASP.NET Core dependency injection out of the box #71

Open robin-83 opened 1 year ago

robin-83 commented 1 year ago

If you have support for EF Core (https://github.com/mehdime/DbContextScope/issues/61) ready, it would be a great addition to support the built in dependency injection framework in ASP.NET: Currently if you only register the implementation like this: builder.Services.AddScoped<IDbContextScopeFactory, DbContextScopeFactory>(); builder.Services.AddScoped<IAmbientDbContextLocator, AmbientDbContextLocator>(); the context must have a parameterless constructor. As DBContextCollection includes the following line: Activator.CreateInstance<TDbContext>().

To support a context with parameters provided by DI (like auto generated from scaffolding), the library could have a default factory like this:

`internal class DBContextLocator : IDbContextFactory { private readonly IServiceProvider _serviceProvider;

    public DBContextLocator(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public TDbContext CreateDbContext<TDbContext>() where TDbContext : class, IDbContext
    {
        return ActivatorUtilities.CreateInstance(_serviceProvider, typeof(TDbContext)) as TDbContext ??
            throw new NotImplementedException(typeof(TDbContext).Name);
    }
}`

Perhabs there are better ways to create the context, but I think you get the idea.