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

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

.Net 6.0. Dependency Injection. How do I inject by type?

问题

ICombiService接口有多个实现。我想根据appsettings.json中的字符串值来注入其中一个实现。可以通过以下方式找到配置的类型:

  1. private static Type? GetConfiguredCombiServiceType(Settings settings)
  2. {
  3. var type = typeof(ICombiService);
  4. var cst = AppDomain.CurrentDomain.GetAssemblies()
  5. .SelectMany(s => s.GetTypes())
  6. .FirstOrDefault(p => !p.IsInterface && type.IsAssignableFrom(p)
  7. && p.Name.Contains(settings.CombiSpecification));
  8. return cst;
  9. }

然后,如何注入配置的类型?我已经进行了广泛的搜索,但似乎找不到相关信息。我希望最终实现类似以下的代码:

  1. var builder = new ServiceCollection()
  2. // 其他依赖项在这里 . . .
  3. .AddTransient<ICombiService>(cs => (ICombiService)combiService)
  4. .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

  1. private static Type? GetConfiguredCombiServiceType(Settings settings)
  2. {
  3. var type = typeof(ICombiService);
  4. var cst = AppDomain.CurrentDomain.GetAssemblies()
  5. .SelectMany(s =&gt; s.GetTypes())
  6. .FirstOrDefault(p =&gt; !p.IsInterface &amp;&amp; type.IsAssignableFrom(p)
  7. &amp;&amp; p.Name.Contains(settings.CombiSpecification));
  8. return cst;
  9. }

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

  1. var builder = new ServiceCollection()
  2. // Other dependencies here . . .
  3. .AddTransient&lt;ICombiService&gt;(cs =&gt; (ICombiService)combiService)
  4. .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

  1. I'm embarrassed to say, the answer is as simple as
  2. var combiService = GetConfiguredCombiServiceType(settings);
  3. then in your builder...
  4. var builder = new ServiceCollection()
  5. .AddTransient(typeof(ICombiService), combiService)
  6. .BuildServiceProvider();
英文:

I'm embarrassed to say, the answer is as simple as

  1. var combiService = GetConfiguredCombiServiceType(settings);

then in your builder...

  1. var builder = new ServiceCollection()
  2. .AddTransient(typeof(ICombiService), combiService)
  3. .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:

确定