在ASP.NET Core中注册HostedService的正确方法。 AddHostedService与AddSingleton [英] Proper way to register HostedService in ASP.NET Core. AddHostedService vs AddSingleton
问题描述
在ASP.NET Core 2.1中注册自定义托管服务的正确方法是什么?例如,我有从名为 MyHostedService
的BackgroundService 。我应该如何注册?
What is proper way to register custom hosted service in ASP.NET Core 2.1? For example I have custom hosted service derived from BackgroundService named MyHostedService
. How should I register it?
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//...
services.AddSingleton<IHostedService, MyHostedService>();
}
或
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//...
services.AddHostedService<MyHostedService>();
}
?
Here we can see first case, but here there is second case.
这些方法是否相等?
推荐答案
它们相似但不完全
AddHostedService
是 Microsoft.Extensions.Hosting.Abstractions
的一部分。
它属于 ServiceCollectionHostedServiceExtensions
类
It belongs to Microsoft.Extensions.Hosting.Abstractions
in the ServiceCollectionHostedServiceExtensions
class
using Microsoft.Extensions.Hosting;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionHostedServiceExtensions
{
/// <summary>
/// Add an <see cref="IHostedService"/> registration for the given type.
/// </summary>
/// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>
/// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>
/// <returns>The original <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)
where THostedService : class, IHostedService
=> services.AddTransient<IHostedService, THostedService>();
}
}
请注意,它使用的是 Transient
生存时间范围,而不是 Singleton
Note it is using Transient
life time scope and not Singleton
内部框架将所有托管服务添加到另一项服务 ( HostedServiceExecutor
)
Internally the framework add all the hosted services to another service (HostedServiceExecutor
)
public HostedServiceExecutor(ILogger<HostedServiceExecutor> logger,
IEnumerable<IHostedService> services) //<<-- note services collection
{
_logger = logger;
_services = services;
}
在启动时是通过 WebHost构造函数。
_applicationServiceCollection.AddSingleton<HostedServiceExecutor>();
这篇关于在ASP.NET Core中注册HostedService的正确方法。 AddHostedService与AddSingleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!