2010-07-05 77 views
6

其中第一种获取客户数据的方法有哪些优势?服务与存储库

ICustomerService customerService = MyService.GetService<ICustomerService>(); 
ICustomerList customerList = customerService.GetCustomers(); 

ICustomerRepository customerRepo = new CustomerRepository(); 
ICustomerList customerList = customerRepo.GetCustomers(); 

如果你明白我的问题,你会不会问的MyService类的实现看起来像;-)

这里是回购的实施.. 。

interface ICustomerRepository 
{ 
    ICustomerList GetCustomers(); 
} 

class CustomerRepository : ICustomerRepository 
{ 
    public ICustomerList GetCustomers() 
    {...} 
} 

回答

4

第一种方法的优点是,通过使用服务定位器,您可以轻松地将t如果需要他执行ICustomerService。使用第二种方法,您必须将每个引用替换为具体类CustomerRepository,才能切换到不同的ICustomerService实现。

更好的方法是使用依赖注入工具,如StructureMapNinject(还有很多其他)来管理您的依赖关系。

编辑:不幸的是许多典型的实现方式是这样的这就是为什么我推荐一个DI框架:

public interface IService {} 
public interface ICustomerService : IService {} 
public class CustomerService : ICustomerService {} 
public interface ISupplerService : IService {} 
public class SupplierService : ISupplerService {} 

public static class MyService 
{ 
    public static T GetService<T>() where T : IService 
    { 
     object service; 
     var t = typeof(T); 
     if (t == typeof(ICustomerService)) 
     { 
      service = new CustomerService(); 
     } 
     else if (t == typeof(ISupplerService)) 
     { 
      service = new SupplierService(); 
     } 
     // etc. 
     else 
     { 
      throw new Exception(); 
     } 
     return (T)service; 
    } 
} 
+0

@Jamie 或LightCore http://lightcore.peterbucher.ch/ ;-) 好对于具有10k LoC的桌面应用程序,我不想使用DI工具也Lightcore是该死的小;-) 你可以告诉我这种ServiceLocator的典型实现?我猜MyService是一个静态类吗? – msfanboy 2010-07-05 18:25:32

+0

啊...所以最后我会有20个其他的如果运行20个不同的服务?地狱这就像编码vb:P btw。如果你对更多的点感兴趣:P http://stackoverflow.com/questions/3181522/c-services-access-the-dataprovider-class-running-the-sql-statements-correct-a – msfanboy 2010-07-05 18:45:50

+0

我认为有这个模式的好实现,但这是我见过的(并且自己写的)。 – 2010-07-05 18:49:29