c# - 如何编写具体类实现相同接口(interface)/服务的服务定位器模式?

标签 c# design-patterns service-locator

考虑以下内容

class ServiceA : IServiceA
    {
        public void SayHelloFromA()
        {
            Console.WriteLine("Hello Service A");
            Console.ReadKey();
        }
    }    
    class ServiceB : IServiceB{ } 
    class ServiceC : IServiceC{ }
    interface IServiceA 
    { 
        void SayHelloFromA(); 
    }
    interface IServiceB{ }
    interface IServiceC{ }

如果我想使用服务定位器模式,提供的示例 here完美运行。

现在假设另一个类实现了 IServiceA 接口(interface),如下所示。

class ServiceA1 : IServiceA
{
    public void SayHelloFromA()
    {
        Console.WriteLine("Hello Service A1");
        Console.ReadKey();
    }
} 

相应地,我需要将服务添加到字典中,如下所示

internal ServiceLocator()    
        {        
            services = new Dictionary<object, object>();         

            this.services.Add(typeof(IServiceA), new ServiceA());
            this.services.Add(typeof(IServiceA), new ServiceA1());     
            this.services.Add(typeof(IServiceB), new ServiceB());        
            this.services.Add(typeof(IServiceC), new ServiceC());    
        } 

这是错误的,因为字典中不能存在重复的键。

那么我该如何解决这个问题呢?应该如何更改数据结构,以便服务定位器可以兼顾两者。

注意~我正在尝试在我的工厂方法中实现服务定位器模式

public class CustomerFactory : ICustomerBaseFactory

{

          public IBaseCustomer  GetCustomer(string  CustomerType)

          { 
                   switch(CustomerType)

                   { 
                             case "1": return  new Grade1Customer(); break;

                             case "2": return new Grade2Customer(); break;

                             default:return null; 
                   } 
          } 
}

具体工厂派生自 IBaseCustomer

谢谢

最佳答案

您是否考虑过由嵌套在顶级字典中的具体类型作为键值的每个抽象类型的字典?

Dictionary<T, Dictionary<T, U>>

这样,您就可以按类型查询顶级字典,然后在子字典中查询实现该类型的所有服务。

例如

var services = new Dictionary<Type, Dictionary<Type, Object>>();

现在您可以向服务字典询问类型:

services.TryGetValue(typeof(IServiceA), componentDictionary);

如果返回 true 那么您就知道 componentDictionary 将包含实现该服务的组件:

foreach (c in componentDictionary.Values) {... }

通过巧妙地使用抽象基类型和泛型,您可以创建比这更强类型的解决方案。然而,这应该工作得相当好,尽管有转换。

关于c# - 如何编写具体类实现相同接口(interface)/服务的服务定位器模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15607880/

相关文章:

c# - 如何将 Entity Framework ICollection 更改为 ObservableCollection?

c# - 如何正确地从派生类复制字段?

c# - 是否可以在应用程序启动时不使用服务定位器来实现依赖注入(inject)?

zend-framework2 - 如何使用 ZF3 设置延迟加载(任何地方都没有 ServiceLocator 模式)

c# - 将 Sprite x,y, width, height 转换为视口(viewport)矩形

C# 数据处理设计模式 : Objects stored in DB via ORM, 直接与数据库一起工作?

SQL 数据库最佳实践 - 使用存档表?

c# - 处理来自外部系统的结果代码查找——如果需要则抛出异常

c - 如何将 memset() 内存设置为特定模式而不是单个字节?

c# - 测试友好的架构