I am writing extension methods for my api to be used in host builder and I need to get an instance of IServiceProvider in it.
I saw that builder.Services.AddDbContext<T>()
has a parameter
(IServiceProvider, DbContextOptionsBuilder)
, so i tought to just add it to my extension method but how?
Lets say I have this extension method:
public static class MyExtensions
{
public static IServiceCollection AddMyServices(this IServiceCollection services, Action<IServiceProvider, MyServicesOptionBuilder> overrides)
{
...
return services;
}
}
and the expected usage is this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMyServices((serviceProvider, config)=>
{
var serviceconfiguration = serviceProvider.GetRequiredService<SomeServiceConfiguration>();
cfg.ConfigureService1(serviceconfiguration);
cfg.ConfigureService2(serviceconfiguration);
....
});
What I don't understand is, who or how is IServiceProvider passed into the Action parameter?
Here is an example I created:
Program.cs:
As you can see, you are the one who will create the
IServiceProvider.