在阅读了很多想法后,包括:
但是如何在不需要包装类的情况下让它工作呢?我将上面讨论的想法组合成以下两种扩展方法。
接口依赖注入
如果您喜欢使用接口 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>();
}
具体类依赖注入
如果你喜欢使用具体的类注入,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>();
}
享受!