如何在泛型类型中注册依赖项注入? (.net核心) [英] How to register dependency injection with generic types? (.net core)
问题描述
我有一个asp.net核心网络应用,在appSettings.json文件中有多个参数.
I have an asp.net core web app with multiple parameters in appSettings.json file.
我不想在构造函数中使用IOptions<MyObject>
的服务.
I didnt' want to have services having IOptions<MyObject>
in the constructor.
我想要构造函数中的MyObject. 所以我找到了以下文章:
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屋!