lundi 26 avril 2021

Dynamic DI in Asp.net Core

I'm using asp.net core and I need to add DI dynamically like bellow:

services.AddTransient<SampleConfig>();

Assembly assembly = myAssembly;

if (assembly == null)
{
     return services;
}

foreach (var type in assembly.ExportedTypes)
{
     var interfaceType = type
        .GetInterfaces().FirstOrDefault(i => i.GetInterfaces().Any(x => x.Name.Contains("IService")));

     if (interfaceType == null)
           continue;

     services.AddTransient(interfaceType, type);
}

My service is like this:

public PriceProvider(
        IHttpClientFactory httpClientFactory,
        ILoggerFactory loggerFactory,
        SampleConfig config)
        : base(httpClientFactory, loggerFactory)
    {
        _httpClient = httpClientFactory.CreateClient();
        _c = config;
    }

My issue is everything works except SampleConfig. It always is null.

Did I miss something?





Aucun commentaire:

Enregistrer un commentaire