如何使用泛型类型注册依赖注入?(.net 核心)

Rém*_*émy 12 c# dependency-injection asp.net-core-mvc .net-core asp.net-core

我在 appSettings.json 文件中有一个带有多个参数的 asp.net 核心 Web 应用程序。

我不想IOptions<MyObject>在构造函数中提供服务。

我想在构造函数中使用 MyObject。所以我找到了以下文章:https : //weblog.west-wind.com/posts/2017/dec/12/easy-configuration-binding-in-aspnet-core-revisited,这很有趣。

但我想更进一步。我想创建一个扩展方法来生成注入。

这是我想做的事情:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 ConfigureServices 方法中我可以调用

services.AddSingletonConfigurationObject<Common.Tools.Configuration.GoogleAnalyticsConfiguration>(Configuration, "GoogleAnalytics");
Run Code Online (Sandbox Code Playgroud)

但我在这一行有一个编译错误:

services.AddSingleton(obj2); 
Run Code Online (Sandbox Code Playgroud)

有人知道我该如何纠正错误吗?

Ton*_*Ngo 28

您可以使用 services.AddScoped 在范围请求中仅使用 1 个实例。因此,与 AddTransient 相比,总体上有所改进

services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
Run Code Online (Sandbox Code Playgroud)

所以我的界面和类看起来像这样

public interface IGenericRepository<T> where T : class
Run Code Online (Sandbox Code Playgroud)
public class GenericRepository<T> : IGenericRepository<T> where T : class
Run Code Online (Sandbox Code Playgroud)

  • 那么注入实例的目标实际上是什么样子的呢? (4认同)
  • 知道为什么这个想法不能与“AddTransient”一起使用吗? (4认同)
  • 由于构造函数注入需要类型参数,是否可以使用构造函数注入?私有只读 IGenericRepository&lt;???&gt; _repository; (2认同)