Skip to content

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

@robin-83

Description

@robin-83

If you have support for EF Core (#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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions