gpt4 book ai didi

c# - 使用 Microsoft DI 在泛型构造函数中注入(inject)基本类型

转载 作者:行者123 更新时间:2023-12-05 05:49:42 26 4
gpt4 key购买 nike

我正在尝试使用依赖注入(inject)来添加具有构造函数参数的通用服务。我需要一般地实现这个:

host.Services.AddSingleton<IService>(x => 
new Service(x.GetRequiredService<IOtherService>(),
x.GetRequiredService<IAnotherOne>(),
""));

这就是我在使用开放泛型方面所做的工作:

host.Services.AddSingleton(typeof(IGenericClass<>), typeof(GenericClass<>));

我无法使用 opengenerics 添加构造函数参数。这是我要添加 DI 的类:

public class GenericClass<T> : IGenericClass<T> where T : class, new()
{
private readonly string _connectionString;
private readonly IGenericClass2<T> _anotherGenericInterface;
private readonly IInterface _anotherInterface;
public GenericClass(
string connectionString,
IGenericClass2<T> anotherGenericInterface,
IInterface anotherInterface)
{
_connectionString = connectionString ??
throw new ArgumentNullException(nameof(connectionString));
_executer = anotherGenericInterface;
_sproc = anotherInterface;
}
}

最佳答案

使用 MS.DI,不可能像使用 IService 那样使用工厂方法构建开放式通用注册。注册。

这里的解决方案是将所有原始构造函数值包装到一个 Parameter Object 中,因此 DI 容器也可以解析它。例如:

// Parameter Object that wraps the primitive constructor arguments
public class GenericClassSettings
{
public readonly string ConnectionString;

public GenericClassSettings(string connectionString)
{
this.ConnectionString =
connectionString ?? throw new ArgumentNullExcpetion();
}
}

GenericClass<T>的构造函数现在可以依赖于新的参数对象:

public GenericClass(
GenericClassSettings settings,
IGenericClass2<T> anotherGenericInterface,
IInterface anotherInterface)
{
_connectionString = settings.ConnectionString;
_executer = anotherGenericInterface;
_sproc = anotherInterface;
}

这允许您注册新的参数对象和开放通用类:

host.Services.AddSingleton(new GenericClassSettings("my connection string"));

host.Services.AddSingleton(typeof(IGenericClass<>), typeof(GenericClass<>));

关于c# - 使用 Microsoft DI 在泛型构造函数中注入(inject)基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70628314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com