我正在使用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");
答案 0 :(得分:65)
您可以提供委托来手动实例化缓存提供程序,也可以直接提供实例:
services.AddSingleton<ICacheProvider>(provider => new RedisCacheProvider("myPrettyLocalhost:6379"));
services.AddSingleton<ICacheProvider>(new RedisCacheProvider("myPrettyLocalhost:6379"));
请注意,即使容器实现了IDisposable,容器也不会显式处理手动实例化的类型。有关详细信息,请参阅有关Disposal of Services的ASP.NET核心文档。
答案 1 :(得分:4)
您可以使用:
services.AddSingleton<ICacheProvider>(x =>
ActivatorUtilities.CreateInstance<RedisCacheProvider>(x, "myPrettyLocalhost:6379"));
依赖注入:ActivatorUtilities将向您的类注入任何依赖。
答案 2 :(得分:2)
如果构造函数还具有应由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>()));
答案 3 :(得分:2)
您可以像下面那样使用。试图用一个例子来解释。
经理班。
public class Manager : IManager
{
ILogger _logger;
IFactory _factory;
public Manager(IFactory factory, ILogger<Manager> logger)
{
_logger = logger;
_factory = factory;
}
}
Startup.cs类
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFactory, Factory>(sp =>
{
var logger = sp.GetRequiredService<ILogger<Factory>>();
var dbContext = sp.GetRequiredService<MyDBContext>();
return new Factory(dbContext, logger);
});
services.AddTransient<IManager, Manager>(sp =>
{
var factory = sp.GetRequiredService<IFactory>();
var logger = sp.GetRequiredService<ILogger<Manager>>();
return new Manager(factory, logger);
});
}
您可以在此处阅读完整的示例。
答案 4 :(得分:0)
晚了一点,但是您可以直接注入一个工厂来创建并公开提供程序类的实例。