Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Late registration of services with asp.net core web api

I have a Web API implementation in ASP.NET Core and I'd like to use the included Dependency Injection. In addition I have late binded assemblies, where I have to load a Type and create an instance of it, which can have dependencies to the main application.

I am trying to load dynamic resources from Assemblies I do not know while startup. So I am using Assembly.Load("name") and look up factory types, that give me the resource reader implementation of the Assembly. So I know the type I need to create an instance of, but I cannot register it to the IServiceCollection and therefore cannot create instances with the ServiceProvider.

So I tried to register my found types to the IServiceCollection which was provided by the framework. For what I registered the ServiceCollection within itself.

// Within Startup.cs
public void ConfigureServices(IServiceCollection services)
{
  services.AddSingleton<IServiceCollection>(services);
}

// A service to register new dependencies later on
public class ServiceRegistrationService : IServiceRegistrationService
{    
  public IServiceCollection Services { get; }
  public IServiceRegistrationService RegisterSelfTransient(Type type)
  {
    Services.AddTransient(type);
    return this;
  }
}

After calling this method like:

ServiceRegistrationService.RegisterSelfTransient(typeof(MyConcreteType));

I'd expect the IServiceProvider to resolve a new instance of my type. Is there a way to register services after leaving the ConfigureServices(IServiceCollection services) method?

like image 294
greg-e Avatar asked Nov 17 '25 02:11

greg-e


1 Answers

After execution of WebApplicationBuilder.Build() in Program.cs's top-level statements, the IServiceCollection turns to read-only one:

public IHost Build()
{
   ...
   // Prevent further modification of the service collection now that the provider is built.
   _serviceCollection.MakeReadOnly();
   ...
}

So it seems no further changes could be introduced after that.

like image 99
Angel Dinev Avatar answered Nov 19 '25 18:11

Angel Dinev