【问题标题】:Service Class should reference other Service Class or just reference other Repository Class?服务类应该引用其他服务类还是只引用其他存储库类?
【发布时间】:2011-11-09 10:50:17
【问题描述】:

我有一个 WCF 服务类 PersonService,它可以将 Person 和他/她的 Address 信息保存到数据库中的 Person 和 Address 表中。
以下是实现的两个版本:

版本 1(存储库版本)

    [ServiceContract]
    class PersonService
    {
        private IPersonRepository _personRepository;

        //by referencing other **repository**
        private IAddressRepository _addressRepository;

        private PersonService(IPersonRepository personRepository, IAddressRepository addressRepository)
        {
            _personRepository = personRepository;
            _addressRepository = addressRepository;
        }

        public void Add(Person person){
            _personRepository.Add(person);

            //by calling method from the **repository** layer
            if(!_addressRepository.Contains(person.Address))
            {
                _addressRepository.Add(person.Address);
            }
        }
    }

版本 2(服务版本)

[ServiceContract]
    class PersonService
    {
        private IPersonRepository _personRepository;

        //by referencing other **service**;
        private IAddressService _addressService;

        private PersonService(IPersonRepository personRepository, IAddressService addressService)
        {
            _personRepository = personRepository;
            _addressService = addressService;
        }
        public void Add(Person person)
        {
            _personRepository.Add(person);

            //by calling method from the **service** layer
            if (!_addressService.Contains(person.Address))
            {
                _addressService.Add(person.Address);
            }
        }
    }

其中哪一个是更好的做法?像 PersonService 这样的 Service 类应该与同一层的接口更多地耦合,还是像 Repository 层这样的较低层?为什么?

【问题讨论】:

    标签: c# wcf architecture repository


    【解决方案1】:

    两个版本相同。 接口名称不应暗示实现细节。

    PersonService 类不关心谁在实现接口(存储库或服务),只要它获得实现接口的对象即可。

    最后,这就是为什么您使用接口而不是直接使用实现它的类的原因。

    如果您正在审阅如何进行依赖注入,我会传递该服务,以防您在 AddressService 中有一些缓存或其他处理。

    【讨论】:

    • 我的意思是,IAddressService 位于 IAddressReposistory 层之上的层中,如果像 PersonService 这样的 Service 类更多地耦合与同一层中的接口,或者更低层,例如作为 Repository 层?
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2011-11-10
    • 1970-01-01
    • 2010-09-29
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多