在DI容器设置过程中,我有多个服务依赖于手动设置。例如,其中一些需要数据库连接字符串。所以不要写
services.AddTransient(typeof(TheInterface), typeof(TheImplementation));
我要做
services.AddTransient<TheInterface>(serviceProvider =>
{
// gather all the constructor parameters here
return new TheImplementation(/* pass in the constructor parameters */);
});
构造函数参数始终相同。我没有写这多次,而是考虑创建这些服务的集合并遍历该集合。我知道我可以使用Activator
类从类型创建新实例,但是我正在努力从类型到泛型的转换。以下代码是用于演示目的的示例代码
public void SetupServices(IServiceCollection services, string databaseConnectionString)
{
IDictionary<Type, Type> servicesTypes = new Dictionary<Type, Type>()
{
{ typeof(MyInterface), typeof(MyImplementation) }
// ... more services here
};
foreach (KeyValuePair<Type, Type> servicesType in servicesTypes)
{
services.AddTransient <??? /* servicesType.Key does not work here */> (serviceProvider =>
{
return Activator.CreateInstance(servicesType.Value, databaseConnectionString /*, other params */);
});
}
}
我正在努力的位置是这条线
services.AddTransient <??? /* servicesType.Key does not work here */>
我如何将服务接口类型转换为通用类型?我什至不确定这个循环是否值得努力...但是目前我有5个服务可以使用它。
我不确定执行通用版本是否正确。可以使用选项模式来固定服务的“手动设置”吗?看起来您正在尝试传递数据库连接字符串。
它可能看起来像
// Options object
public class DatabaseOptions {
public string ConnectionString {get;set;}
}
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
[...]
// From configuration (appsettings.json)
services.Configure<DatabaseOptions>(Configuration.GetSection("Database"));
// OR directly
services.Configure<DatabaseOptions>(x => x.ConnectionString = "SomeString");
}
// The service
public class SomeService {
public SomeService(IOptions<DatabaseOptions> dbOptions) {
var connectionString = dbOptions.Value.ConnectionString;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句