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

查看:41
本文介绍了在 ASP.NET Core 中注册 HostedService 的正确方法.AddHostedService 与 AddSingleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ASP.NET Core 2.1 中注册自定义托管服务的正确方法是什么?例如,我有一个源自 BackgroundService 名为 MyHostedService.我应该如何注册?

public IServiceProvider ConfigureServices(IServiceCollection services){//...services.AddSingleton();}

public IServiceProvider ConfigureServices(IServiceCollection services){//...services.AddHostedService();}

?

这里我们可以看到第一种情况,但是这里 还有第二种情况.

这些方法是否相同?

解决方案

更新

<块引用>

在 .Net Core 2.2 和 3.1 之间的某个地方,行为发生了变化,AddHostedService 现在添加了单例服务,而不是之前的瞬态服务.信用 - 评论 来自 LeonG

公共静态类 ServiceCollectionHostedServiceExtensions{///<总结>///添加一个 <see cref="IHostedService"/>给定类型的注册.///</总结>///<typeparam name=THostedService">An <see cref=IHostedService"/>注册.///注册.</param>///<returns>原始的<see cref="IServiceCollection"/>.</returns>public static IServiceCollection AddHostedService<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THostedService>(这个IServiceCollection服务)其中 THostedService : 类,IHostedService{services.TryAddEnumerable(ServiceDescriptor.Singleton());退货服务;}///<总结>///添加一个 <see cref="IHostedService"/>给定类型的注册.///</总结>///<typeparam name=THostedService">An <see cref=IHostedService"/>注册.///注册.</param>///<param name="implementationFactory">用于创建服务实现的新实例的工厂.</param>///<returns>原始的<see cref="IServiceCollection"/>.</returns>public static IServiceCollection AddHostedService(这个IServiceCollection服务,Func implementationFactory)其中 THostedService : 类,IHostedService{services.TryAddEnumerable(ServiceDescriptor.Singleton(implementationFactory));退货服务;}}

参考 ServiceCollectionHostedServiceExtensions


原答案

它们相似但不完全

AddHostedServiceMicrosoft.Extensions.Hosting.Abstractions 的一部分.

它属于 ServiceCollectionHostedServiceExtensions

使用 Microsoft.Extensions.Hosting;命名空间 Microsoft.Extensions.DependencyInjection{公共静态类 ServiceCollectionHostedServiceExtensions{///<总结>///添加一个 <see cref="IHostedService"/>给定类型的注册.///</总结>///<typeparam name=THostedService">An <see cref=IHostedService"/>注册.///注册.</param>///<returns>原始的<see cref="IServiceCollection"/>.</returns>public static IServiceCollection AddHostedService(这个 IServiceCollection 服务)其中 THostedService : 类,IHostedService=>services.AddTransient();}}

注意它使用的是 Transient 生命周期范围而不是 Singleton

框架在内部将所有托管服务添加到另一个服务 (HostedServiceExecutor)

public HostedServiceExecutor(ILogger logger,IEnumerableservices)//<<-- 注意服务集合{_logger = 记录器;_services = 服务;}

在启动时通过 WebHost 构造器.

_applicationServiceCollection.AddSingleton();

What is the proper way to register a custom hosted service in ASP.NET Core 2.1? For example, I have a custom hosted service derived from BackgroundService named MyHostedService. How should I register it?

public IServiceProvider ConfigureServices(IServiceCollection services)
{           
    //...
    services.AddSingleton<IHostedService, MyHostedService>();
}

or

public IServiceProvider ConfigureServices(IServiceCollection services)
{           
    //...
    services.AddHostedService<MyHostedService>();
}

?

Here we can see the first case, but here there is a second case.

Are these methods equal?

解决方案

Update

Somewhere between .Net Core 2.2 and 3.1 the behavior has changed, AddHostedService is now adding a Singleton instead of the previous Transient service. Credit - Comment by LeonG

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<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THostedService>(this IServiceCollection services)
        where THostedService : class, IHostedService
    {
        services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, THostedService>());

        return services;
    }

    /// <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>
    /// <param name="implementationFactory">A factory to create new instances of the service implementation.</param>
    /// <returns>The original <see cref="IServiceCollection"/>.</returns>
    public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services, Func<IServiceProvider, THostedService> implementationFactory)
        where THostedService : class, IHostedService
    {
        services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService>(implementationFactory));

        return services;
    }
}

Reference ServiceCollectionHostedServiceExtensions


Original Answer

They are similar but not completely

AddHostedService is part of Microsoft.Extensions.Hosting.Abstractions.

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>();
    }
}

Note it is using Transient life time scope and not Singleton

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;
}

at startup that is a singleton via the WebHost Constructor.

_applicationServiceCollection.AddSingleton<HostedServiceExecutor>();

这篇关于在 ASP.NET Core 中注册 HostedService 的正确方法.AddHostedService 与 AddSingleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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