服务与存储库

时间:2010-07-05 18:03:13

标签: c# repository service

第一种获取客户数据的方法的优势在哪里?

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

VS

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

如果您理解我的问题,您将不会问MyService类的实现如何; - )

这里是Repo的实施......

interface ICustomerRepository
{
    ICustomerList GetCustomers();
}

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

1 个答案:

答案 0 :(得分:4)

第一种方法的优点是,通过使用服务定位器,您可以根据需要轻松交换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;
    }
}
相关问题