【发布时间】:2022-01-07 23:34:35
【问题描述】:
我正在尝试使用依赖注入来添加具有构造函数参数的通用服务。我需要实现这个,一般来说:
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;
}
}
【问题讨论】:
-
连接字符串总是一样的吗?
-
是的,我已经预先运行了一些代码来获取它。 @ChiefTwoPencils
标签: c# asp.net-core dependency-injection .net-5 open-generics