【问题标题】:Service vs. Repository服务与存储库
【发布时间】:2010-07-05 18:03:12
【问题描述】:

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

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

对比

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

如果你理解我的问题,你就不会问 MyService 类的实现是怎样的 ;-)

这里是 Repo 的实现...

interface ICustomerRepository
{
    ICustomerList GetCustomers();
}

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

【问题讨论】:

    标签: c# repository service


    【解决方案1】:

    第一种方法的优点是,通过使用服务定位器,您可以在需要时轻松更换 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;
        }
    }
    

    【讨论】:

    • @Jamie 或 LightCore lightcore.peterbucher.ch ;-) 对于具有 10k LoC 的桌面应用程序来说,我不想使用 DI 工具,Lightcore 也太小了 ;-) 你能告诉我一个典型的实现吗这样的ServiceLocator?我猜 MyService 是一个静态类吧?
    • 啊...所以如果运行 20 种不同的服务,我最终将拥有 20 种其他服务??这就像编码 vb :P 顺便说一句。如果您对更多积分感兴趣:P stackoverflow.com/questions/3181522/…
    • 我认为这种模式有很好的实现,但这是我见过的(也是我自己写的)。
    • 那么你为什么不使用 DI 工具并为自己编写这些东西呢?
    • 我年轻而愚蠢。我今天不会写那种代码,但我过去写过类似的代码。
    猜你喜欢
    • 2011-05-21
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多