c# - 启动后向 IServiceCollection 注册类

标签 c# .net-core dependency-injection

在我的应用程序中,我想在启动后注册一堆服务。

晚课:

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

当然还要注册 LateClass 本身:

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

但是 IServiceCollection 会破坏我的应用程序,并且我遇到了无法解决的异常。

最佳答案

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

您可以根据需要使 ConfigurationService 变得尽可能复杂(注入(inject)其他已注入(inject)其他内容的服务),直到它具有循环依赖关系。

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

关于c# - 启动后向 IServiceCollection 注册类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62052296/

相关文章:

c# - 只有 1 个 Main 方法的 XUnit 测试项目 : "Program has more than one entry point defined."

c# - 如何从 .net 核心 IoC 容器中删除默认服务?

c# - 为什么在包含等待的方法中使用 Task.FromResult<T>(T result) ?

java - Dagger 在 Android 应用程序中生成重复的 `XXXDialogFragment_MembersInjector` 类(程序类型已存在)

java - 为什么 Guice 不能绑定(bind)中间依赖项?

c# - 序列化 System.Windows.Media.ImageSource 对象

C# 元组列表多重排序

java - 依赖项应该注入(inject)一次还是每个对象中

c# - 在内存中没有负载基础的情况下使用 LinqToSql

c# - 关于从 ASP.NET 2.0 到 ASP.NET 3.5 MVC 的区别的问题