代码之家  ›  专栏  ›  技术社区  ›  PassionateDeveloper

启动后用IServiceCollection注册类

  •  0
  • PassionateDeveloper  · 技术社区  · 6 年前

    晚班:

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

    当然,注册LateClass本身:

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

    0 回复  |  直到 6 年前
        1
  •  1
  •   Yehor Androsov    6 年前

    在评论中回答OP的问题应该如何处理动态配置。

    您可以使您的ConfigurationService尽可能地复杂化(注入其他注入了其他内容的服务),直到它具有循环依赖性。

    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
            }
        }
    }