英文:
.Net 6.0. Dependency Injection. How do I inject by type?
问题
ICombiService接口有多个实现。我想根据appsettings.json中的字符串值来注入其中一个实现。可以通过以下方式找到配置的类型:
private static Type? GetConfiguredCombiServiceType(Settings settings)
{
var type = typeof(ICombiService);
var cst = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.FirstOrDefault(p => !p.IsInterface && type.IsAssignableFrom(p)
&& p.Name.Contains(settings.CombiSpecification));
return cst;
}
然后,如何注入配置的类型?我已经进行了广泛的搜索,但似乎找不到相关信息。我希望最终实现类似以下的代码:
var builder = new ServiceCollection()
// 其他依赖项在这里 . . .
.AddTransient<ICombiService>(cs => (ICombiService)combiService)
.BuildServiceProvider();
但这是一个多余的类型转换,不起作用。这种事情在AutoFac和Ninject中很容易实现,但我似乎找不到有关Microsoft DI实现的任何信息。非常感谢任何帮助。
英文:
I have multiple implementations of an ICombiService interface. I want to inject one of these implementations based on a string value from appsettings.json. I can find the configured type thus
private static Type? GetConfiguredCombiServiceType(Settings settings)
{
var type = typeof(ICombiService);
var cst = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.FirstOrDefault(p => !p.IsInterface && type.IsAssignableFrom(p)
&& p.Name.Contains(settings.CombiSpecification));
return cst;
}
How do I then inject this configured type? I have searched extensively, (maybe I'm wording my search wrong) but not finding anything. I want to end up with something like the following
var builder = new ServiceCollection()
// Other dependencies here . . .
.AddTransient<ICombiService>(cs => (ICombiService)combiService)
.BuildServiceProvider();
but that's a spurious cast and does not work. This kind of thing is easy enough with AutoFac and Ninject but I can't seem to find any info on Microsofts implementation of DI. Any help greatly appreciated.
答案1
得分: 1
I'm embarrassed to say, the answer is as simple as
var combiService = GetConfiguredCombiServiceType(settings);
then in your builder...
var builder = new ServiceCollection()
.AddTransient(typeof(ICombiService), combiService)
.BuildServiceProvider();
英文:
I'm embarrassed to say, the answer is as simple as
var combiService = GetConfiguredCombiServiceType(settings);
then in your builder...
var builder = new ServiceCollection()
.AddTransient(typeof(ICombiService), combiService)
.BuildServiceProvider();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论