Can I get a service from container before adding a DbContext to the services?

Viewed 474

I have an ASP.NET Core 3.1 based application. I would typically register my DbContext using something like this

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(scope =>
   {
       scope.UseMySql(Configuration.GetConnectionString("ConnectionString"));
   });

   // ...
}

However, in this case, I am trying to use OrchardCore which is built on the top of the ASP.NET Core 3.1 framework. I need to use the IDbConnectionAccessor service to get me an instance of the DbConnection. So, I can register the AppDbContext, I want to retrieve the IDbConnectionAccessor.

I tried this

public void ConfigureServices(IServiceCollection services)
{
   services.AddDbContext<AppDbContext>(scope =>
   {
       var accessor = scope.GetRequiredService<IDbConnectionAccessor>();
       scope.UseMySql(accessor.CreateConnection());
   });

   // ...
}

But the line var accessor = scope.GetRequiredService<IDbConnectionAccessor>(); is giving me the following error

Error CS1929 'DbContextOptionsBuilder' does not contain a definition for 'GetRequiredService' and the best extension method overload 'ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider)' requires a receiver of type 'IServiceProvider'

How can I get an instance of IDbConnectionAccessor before the AppDbContext is registered?

1 Answers

AddDbContext comes with an overload for a callback that takes both IServiceProvider and DbContextOptionsBuilder.

Here's an example that shows how to use it:

services.AddDbContext<AppDbContext>((sp, options) =>
{
    var dbConnectionAccessor = sp.GetRequiredService<IDbConnectionAccessor>();
    options.UseMySql(dbConnectionAccessor.CreateConnection());
});
Related