最近我一般将它创建为一个IHostedService
,如果需要初始化,因为对我来说,让服务自己处理初始化似乎更合理,而不是在外部进行。
你甚至可以使用BackgroundService
代替IHostedService
,因为它们非常相似,只需要实现ExecuteAsync
即可。
这里是它们的文档:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services
下面是如何添加该服务以便你可以直接注入它的示例:
services
.AddHostedService<MyService>()
.AddSingleton<MyService>(x => x
.GetServices<IHostedService>()
.OfType<MyService>()
.First());
一个简单服务的示例:
public class MyService : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
我后来创建了一些扩展方法,因为我需要再次使用相同的模式
public static class HostedServiceExtensions
{
public static IServiceCollection AddHostedServiceAsService<T>(this IServiceCollection services) where T : class, IHostedService
=> services.AddHostedService<T>().AddSingleton(x => x.GetServices<IHostedService>().OfType<T>().First());
public static IServiceCollection AddHostedServiceAsService<T>(this IServiceCollection services, Func<IServiceProvider, T> factory) where T : class, IHostedService
=> services.AddHostedService(factory).AddSingleton(x => x.GetServices<IHostedService>().OfType<T>().First());
}
用法类似于
services.AddHostedServiceAsService<MyService>();
services.AddHostedServiceAsService<MyService>(x => new MyService());
new Foo()
并在ConfigureServices
方法中进行注册。 - adem caglinFoo
有依赖关系,所以它没有默认构造函数。 - Cody Stott