在 ASP.NET Core 中注册 HostedService 的正确方法.AddHostedService 与 AddSingleton

编程入门 行业动态 更新时间:2024-10-18 06:09:16
本文介绍了在 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(这个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

原答案

它们相似但不完全

AddHostedService 是 Microsoft.Extensions.Hosting.Abstractions 的一部分.

它属于 Microsoft.Extensions.Hosting.Abstractions.Abstractions/ServiceCollectionHostedServiceExtensions.cs" rel="nofollow noreferrer">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

本文发布于:2023-11-14 04:18:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   Core   NET   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!