我正在使用DI的vNext实现。如何将参数传递给构造函数?例如,我有一门课:
public class RedisCacheProvider : ICacheProvider
{
private readonly string _connectionString;
public RedisCacheProvider(string connectionString)
{
_connectionString = connectionString;
}
//interface methods implementation...
}及服务登记册:
services.AddSingleton<ICacheProvider, RedisCacheProvider>();如何将参数传递给RedisCacheProvider类的构造函数?例如,Autofac:
builder.RegisterType<RedisCacheProvider>()
.As<ICacheProvider>()
.WithParameter("connectionString", "myPrettyLocalhost:6379");发布于 2016-01-17 02:10:51
发布于 2019-12-18 09:55:56
如果构造器还具有依赖项,而依赖项应由DI解决,则可以使用以下方法:
public class RedisCacheProvider : ICacheProvider
{
private readonly string _connectionString;
private readonly IMyInterface _myImplementation;
public RedisCacheProvider(string connectionString, IMyInterface myImplementation)
{
_connectionString = connectionString;
_myImplementation = myImplementation;
}
//interface methods implementation...
}Startup.cs:
services.AddSingleton<IMyInterface, MyInterface>();
services.AddSingleton<ICacheProvider>(provider =>
RedisCacheProvider("myPrettyLocalhost:6379", provider.GetService<IMyInterface>()));发布于 2020-01-25 13:56:49
您可以使用:
services.AddSingleton<ICacheProvider>(x =>
ActivatorUtilities.CreateInstance<RedisCacheProvider>(x, "myPrettyLocalhost:6379"));依赖注入: ActivatorUtilities将向类注入任何依赖项。
下面是到MS文档的链接:Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance
另外:有关更多信息,请参见@poke的答案这里。基本上,它是从所提供的服务和您传递的任何其他参数中提取出来的,就像存储构造函数一样。
https://stackoverflow.com/questions/34834295
复制相似问题