服务与存储库

msf*_*boy 6 c# service repository

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

ICustomerService customerService = MyService.GetService<ICustomerService>();
ICustomerList customerList = customerService.GetCustomers();
Run Code Online (Sandbox Code Playgroud)

ICustomerRepository customerRepo = new CustomerRepository();
ICustomerList customerList = customerRepo.GetCustomers();
Run Code Online (Sandbox Code Playgroud)

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

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

interface ICustomerRepository
{
    ICustomerList GetCustomers();
}

class CustomerRepository : ICustomerRepository
{
    public ICustomerList GetCustomers()
    {...}
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*Ide 5

第一种方法的优点是,通过使用服务定位器,您可以根据需要轻松更换 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;
    }
}
Run Code Online (Sandbox Code Playgroud)