In my project I'm loading some dll assemblies and these assemblies contains controllers as well as services need to be injected in our DI container.
I tried to find a solutions for a days using default dotnet core DI or Autofac without any results.
I understand this is not good practice to update DI in runtime, but I hope if I can found a good solution.
I have got another way but it saves the services in config file and it is required to restart the app to load the config in beginning to register the services.
Example of my code
public class ServiceFactory : IServiceProvider
{
public static IServiceCollection services { get; set; }
public static IServiceProvider serviceProvider { get; private set; }
static ServiceFactory()
{
services = new ServiceCollection();
serviceProvider = services.BuildServiceProvider();
}
public static void ConfigureServices(IServiceCollection _services)
{
services = _services;
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public static void Register()
{
services.AddTransient<IRepo, Repo>();
}
public static void Update()
{
serviceProvider = services.BuildServiceProvider();
}
public object GetService(Type serviceType)
{
return serviceProvider.GetService(serviceType);
}
}