在ASP.NET Core中注册HostedService的正确方法。 AddHostedService与AddSingleton [英] Proper way to register HostedService in ASP.NET Core. AddHostedService vs AddSingleton

本文介绍了在ASP.NET Core中注册HostedService的正确方法。 AddHostedService与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 的一部分。

它属于Microsoft.Extensions.Hosting.Abstractions .com / aspnet / Hosting / blob / master / src / Microsoft.Extensions.Hosting.Abstractions / ServiceCollectionHostedServiceExtensions.cs rel = noreferrer> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆