考虑以下内容
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/