簡體   English   中英

Asp.net 內核如何注冊也包含自定義接口的 IHostedService

[英]Asp.net core How to Register IHostedService which also Contains a Custom Interface

如何屬性注冊一個包含IHostedService和 IMyInterface 之類的自定義接口的IMyInterface

如在

class BackgroundTaskScheduler: BackgroundService, ITaskScheduler {...}

如果配置如下:

services.AddHostedService<BackgroundTaskScheduler>();

然后嘗試將其注入客戶端,如下所示:

public class Foo
{
    Foo(ITaskScheduler taskScheduler) {...}
}

生成一個錯誤,指出 ASP.net 無法解析BackgroundTaskScheduler ,為什么?

在閱讀了很多想法后,包括:

但是如何在不需要包裝器 class 的情況下使其工作? 我將上面討論的想法組合成以下兩種擴展方法。

接口依賴注入

如果您喜歡使用接口 DI,如Bar.Bar(IFoo foo)中,那么使用這個:

        /// <summary>
        /// Used to register <see cref="IHostedService"/> class which defines an referenced <typeparamref name="TInterface"/> interface.
        /// </summary>
        /// <typeparam name="TInterface">The interface other components will use</typeparam>
        /// <typeparam name="TService">The actual <see cref="IHostedService"/> service.</typeparam>
        /// <param name="services"></param>
        public static void AddHostedApiService<TInterface, TService>(this IServiceCollection services)
            where TInterface : class
            where TService : class, IHostedService, TInterface
        {
            services.AddSingleton<TInterface, TService>();
            services.AddSingleton<IHostedService>(p => (TService) p.GetService<TInterface>());
        }

用法:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHostedApiService<ITaskScheduler, BackgroundTaskScheduler>();
        }

具體class依賴注入

如果你喜歡使用具體的 class 注入,就像在Bar.Bar(Foo foo)中一樣,那么使用:

        /// <summary>
        /// Used to register <see cref="IHostedService"/> class which defines an interface but will reference the <typeparamref name="TService"/> directly.
        /// </summary>
        /// <typeparam name="TService">The actual <see cref="IHostedService"/> service.</typeparam>
        public static void AddHostedApiService<TService>(this IServiceCollection services)
            where TService : class, IHostedService
        {
            services.AddSingleton<TService>();
            services.AddSingleton<IHostedService>(p => p.GetService<TService>());
        }

用法:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHostedApiService<BackgroundTaskScheduler>();
        }

享受!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM