![](/img/trans.png)
[英]How to register services with dependency container services by reflection in c#
[英]How to register all Hosted Services with reflection in dotnet 5.0
我正在尝试使用反射将我的所有工作服务注册为dotnet 5.0 中的托管服务。
我已经以这种方式注册了我所有项目的应用程序服务:
private static void RegisterApplicationServices(IServiceCollection services)
{
var applicationServices = (Assembly.GetAssembly(typeof(ConfigurationService)))
.GetTypes()
.Where(x => !x.IsInterface &&
x.GetInterface(typeof(IApplicationService).Name) != null);
foreach (var serviceType in applicationServices)
{
var type = serviceType.UnderlyingSystemType;
services.AddTransient(type.GetInterface($"I{type.Name}"), type);
}
}
但是当涉及到托管服务时,它不起作用。 我需要某种方式将所有工作人员注册为托管服务。
services.AddHostedService<WokrerService1>();
services.AddHostedService<WokrerService2>();
services.AddHostedService<WokrerService3>();
services.AddHostedService<WokrerService4>();
services.AddHostedService<WokrerService5>();
services.AddHostedService<WokrerService6>();
private static void RegisterHostedServices(IServiceCollection services)
{
//What should I do here?
}
所有的工人都继承自一个BaseWorker类
public abstract class BaseWorkerService<TWorkerService> :
BackgroundService, IAppHostedService where TWorkerService : class
{
}
public class TransactionSubscriberService :
BaseWorkerService<TransactionSubscriberService>
{
}
我很感激任何帮助。
所以, AddHostedService
只添加了IHostedService
类型和实现类型的单例。 这里没有魔法
var types = someAssembly
.GetTypes()
// or however you want to target classes
.Where(t => t.IsSubclassOf(typeof(IHostedService)));
foreach (var type in types)
services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IHostedService), type));
但是,问题似乎是您不能阻止StartAsync
,否则其他服务将无法启动
public Task StartAsync(CancellationToken cancellationToken)
{
Task.Run(() => DoSomething);
return Task.CompletedTask;
}
免责声明:我从来没有尝试过这个,代码没有经过测试,它只是从简要查看源代码中得到的理论答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.