在 .net core 3 之前,您可以使用一个配置类,通过 DI 将其注入到服务中。您的配置类可能如下所示:
class IntegrationConfig
{
public int Timeout { get; set; }
public string Name { get; set; }
}
然后您需要将此配置添加到 DI 系统中:
services.AddSingleton(new IntegrationConfig
{
Timeout = 1234,
Name = "Integration name"
})
在类
IntegrationService
中,您需要添加一个构造函数,该构造函数接受一个配置对象作为参数:
public IntegrationService(IntegrationConfig config)
{
}
这基本上是你所需要的。在我的观点中,它不是最好的解决方案,在
.net core 3
中,你可以简单地使用工厂函数添加 HostedService,但我认为如果你使用
.net core 2.2
或以下版本,则这样做是最好的选择。
编辑:
在评论中,Kirk Larkin 提到了这一点:
“你可以模拟重载。它只是 AddTransient() 的包装,当然支持工厂函数方法。”
对于这个问题,您可能需要查看当前可访问的重载,该重载位于
此处:
/// <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;
}
请注意,
更改此文件的最新提交是在6月3日,并且已标记为 .net core 3 的预览版6和预览版7。由于我从未听说过
TryAddEnumerable
并且不是微软员工,我不知道你是否可以直接翻译它。
仅仅通过查看
AddTransient
的当前实现并深入研究几个文件,我很遗憾无法清晰地画出线条,以便能够给出你当前可以通过
.net core 3
获得的确切功能。
我提供的解决方法仍然有效,并且根据情况似乎是可接受的。
services.AddHostedService<IntegrationService>(sp => new IntegrationService(...));
中的sp
代表了IServiceProvider
,您也可以使用它来获取信息以实例化托管服务。如果您需要其他选项,请考虑添加配置选项或类似选项,然后可以通过构造函数注入,这样您就不必手动执行此操作。此重载在 .net core 3 preview6 中存在,但在 .net core 2.2 中不存在。因为您没有指定使用的版本,所以我加了注释。 - JoeliusAddTransient<IHostedService, TWhatever>()
的一个包装器,当然支持工厂函数方法。 - Kirk Larkin