c# - 启动后向 IServiceCollection 注册类
问题描述
在我的应用程序中,我有一堆要在启动后注册的服务。
晚课:
public LateClass(IServiceCollection col)
{
col.AddTransient<IEventHandler, JsonPackageUpdated>();
}
当然还要注册 LateClass 本身:
public void ConfigureServices(IServiceCollection services)
{
col.AddTransient<LateClass>();
}
但是 IServiceCollection 会破坏我的应用程序,并且我遇到了一个我无法解决的异常。
解决方案
在评论中回答 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
}
}
}
推荐阅读
- spring - Spring Data Cassandra 不处理原始 UDTS,不抛出合适的转换器异常
- javascript - 无法从 React 中的路径渲染图像
- postgresql - 使用匿名函数更改 work_mem 失败
- android - 如何在android中的datepicker中禁用所选日期的所有先前日期
- c++ - 设置了 MSB 的第一个字节的索引
- r - 构建一个简单的数据框(DADA2 Pipeline 过渡到 Phyloseq)
- python - LinkedList isPalindrome 检查总是返回 True
- node.js - 如何避免为 Web 构建加载 Expo 通知包?
- algorithm - 使用树的工作面试问题,要保存哪些数据?
- python - AttributeError:“str”对象没有属性“as_widget”