如何使用泛型类型注册依赖注入?(.net 核心) [英] How to register dependency injection with generic types? (.net core)
问题描述
我在 appSettings.json 文件中有一个带有多个参数的 asp.net 核心 Web 应用程序.
I have an asp.net core web app with multiple parameters in appSettings.json file.
我不想让服务在构造函数中包含 IOptions
.
I didnt' want to have services having IOptions<MyObject>
in the constructor.
我想在构造函数中使用 MyObject.所以我找到了以下文章:https://weblog.west-wind.com/posts/2017/dec/12/easy-configuration-binding-in-aspnet-core-revisited 很有趣.
I wanted MyObject in the constructor. So I found the following article: https://weblog.west-wind.com/posts/2017/dec/12/easy-configuration-binding-in-aspnet-core-revisited which is very interesting.
但我想更进一步.我想创建一个扩展方法来生成注入.
But I want to go further. I would like to create an extension method to generate the injection.
这是我想要做的:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Common.WebTools.Extensions
{
public static class IServiceCollectionExtensions
{
public static IServiceCollection AddSingletonConfigurationObject<T>(this IServiceCollection services,
IConfiguration configuration,
string appSettingsKey) where T:new()
{
var obj2 = new T();
configuration.Bind(appSettingsKey, obj);
services.AddSingleton(obj2); //compilation failed
return services;
}
}
}
然后在我的 ConfigureServices 方法中我可以调用
And then in my ConfigureServices method I can call
services.AddSingletonConfigurationObject<Common.Tools.Configuration.GoogleAnalyticsConfiguration>(Configuration, "GoogleAnalytics");
但是我在这一行有一个编译错误:
But I Have a compliation error on this line:
services.AddSingleton(obj2);
有人知道我该如何纠正错误吗?
Does somebody know how could I correct the error?
推荐答案
您可以使用 services.AddScoped 在范围请求中仅使用 1 个实例.因此,与 AddTransient 相比,总体上有所改进
You can use services.AddScoped to use only 1 instance in the scope request. So in general improvement compare to AddTransient
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
所以我的界面和类看起来像这样
So my interface and class will look like this
public interface IGenericRepository<T> where T : class
public class GenericRepository<T> : IGenericRepository<T> where T : class
这篇关于如何使用泛型类型注册依赖注入?(.net 核心)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!