.Net 6.0 依赖注入。如何按类型注入?

huangapple go评论80阅读模式
英文:

.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 =&gt; s.GetTypes())
		.FirstOrDefault(p =&gt; !p.IsInterface &amp;&amp; type.IsAssignableFrom(p) 
											&amp;&amp; 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&lt;ICombiService&gt;(cs =&gt; (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();

huangapple
  • 本文由 发表于 2023年3月3日 18:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定