【问题标题】:Dependency Injection - interfaces in a Dictionary c#依赖注入 - 字典中的接口 c#
【发布时间】:2023-01-19 13:28:11
【问题描述】:

我想将 {key, interface}IDictionary 注入构造函数,但我不知道如何在 program.cs 中设置它

我可以启动接口,也可以启动 IDictionary,但我不知道如何组合它们。

任何建议,将不胜感激。

附加上下文:

所以我需要注入我的服务

我需要注入服务,例如,

s.AddTransient<IFooService, AFooService>();
s.AddTransient<IFooService, BFooService>();

但在我想要的构造函数中

public MyClass(IDictionary<string, IFooService> fooServices)

【问题讨论】:

  • services.AddSingleton(myDictionary);?你为什么首先要这样做?
  • 您不应该将通用集合接口注册为服务。为什么不能定义一个普通的服务接口呢?
  • 接口字典首先包含什么?如果你想存储接口类型,你必须使用Dictionary&lt;whatever,Type&gt;。没有办法说类型是接口,也没有多大意义。您不能实例化接口的实例。如果你想存储实现特定接口的实例,你需要Dictionary&lt;whatever,IMyInterface&gt;
  • 这听起来像XY Problem。你有一个问题 X 并假设 Y 是解决方案(注册一个字典......某物)。当这不起作用时,你要求 Y,而不是真正的问题 X。这里的 X 是什么?如果按名称注册服务就可以解决吗?这个已经支持了
  • @EnenDaveyBoy string 在这里代表什么?

标签: c# dependency-injection interface .net-6.0 idictionary


【解决方案1】:
services.AddTransient<MyClass>();
services.AddTransient<AFooService>();
services.AddTransient<BFooService>();

services.AddTransient<IDictionary<string, IFooService>>(sp =>
    new Dictionary<string, IFooService>
    {
        { "A", sp.GetRequiredService<AFooService>() },
        { "B", sp.GetRequiredService<BFooService>() },
    });
``

【讨论】:

    【解决方案2】:

    有点侵入性的替代方法是向IFooService 添加一个关键属性。然后你可以有 MEDI 枚举服务:

    interface IFooService
    {
        string FooKey { get; }
        // ... void Work(); ...
    }
    
    class MyClass
    {
        private IDictionary<string, IFooService> dict;
    
        public MyClass(IEnumerable<IFooService> fooServices) 
        {
            dict = fooServices.ToDictionary(foo => foo.FooKey);
        }
    }
    
    class Startup
    {
        public void Configure(IServiceCollection s) 
        {
            // you can keep the initialization as-is. DI will populate IEnumerable
            s.AddTransient<IFooService, AFooService>();
            s.AddTransient<IFooService, BFooService>();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-10
      • 2010-11-10
      • 2023-03-23
      • 2012-11-28
      • 2016-06-11
      • 2018-09-02
      • 1970-01-01
      • 2011-07-31
      相关资源
      最近更新 更多