【发布时间】:2013-03-14 12:36:36
【问题描述】:
考虑以下
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 接口。
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
派生的位置谢谢
【问题讨论】:
-
您将如何检索特定的实现?服务定位器的重点是在不知道是哪个的情况下为您提供 IServiceA 的实现。在您的示例中,您将如何调用服务定位器来获得特定的实现? (假设您可以有一个带有重复项的键控容器)
标签: c# design-patterns service-locator