Search code examples
c#.net-coredependency-injection

Register class with IServiceCollection after startup


In my application I have a bunch of services I want to register after the startup.

LateClass :

public LateClass(IServiceCollection col)
{
    col.AddTransient<IEventHandler, JsonPackageUpdated>();
}

And register the LateClass itself of course:

 public void ConfigureServices(IServiceCollection services)
 {
     col.AddTransient<LateClass>();
 }

But the IServiceCollection will break my application and I got an exception that I can't resolve it.


Solution

  • Answering OP's question in comments how dynamic configuration should be handled.

    You can make your ConfigurationService as much compex as you want (inject other services that have something else injected) until it has circular dependency.

    using Microsoft.Extensions.DependencyInjection;
    using System;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var collection = new ServiceCollection();
    
                collection.AddTransient<ConfigurationService>();
                collection.AddTransient<EventProcessService>();
    
    
                var serviceProvider = collection.BuildServiceProvider();
    
                var eventService = serviceProvider.GetService<EventProcessService>();
    
                eventService.ProcessEvent(0);
            }
        }
    
        public class ConfigurationService
        {
            public ConfigurationService(
                    // you could use whatever configuration provider you have: db context for example
                )
            {
            }
    
            public string GetSettingBasedOnEventType(int eventType)
            {
                switch (eventType)
                {
                    case 0:
                        return "Some setting value";
                    case 1:
                        return "Some other setting value";
                    default:
                        return "Not found";
                }
            }
        }
    
        public class EventProcessService
        {
            private readonly ConfigurationService configurationService;
    
            public EventProcessService(ConfigurationService configurationService)
            {
                this.configurationService = configurationService;
            }
    
            public void ProcessEvent(int eventType)
            {
                var settingForEvent = configurationService.GetSettingBasedOnEventType(eventType);
    
                // process event with your setting
            }
        }
    }