DTO 和服务之间的调用

Bre*_*tin 5 c# architecture dto service-layer

假设我的服务层中有两个服务,ServiceA并且ServiceB每个都有一个接口(IServiceAIServiceB分别)。

UI 层仅引用从其方法返回DTO的服务接口。具体的服务类负责将域模型 (EF POCO) 映射到 DTO。

ServiceA需要的依赖关系IServiceB通过依赖注入使用IoC容器中,为了调用该服务的一些方法。

这样做有几个问题:

  1. 与 DTO 之间的不必要/重复映射只是为了调用方法和/或使用结果。

  2. 将调用方法与被调用方法的输入参数和返回类型的 DTO 契约紧密耦合。

最初我想将逻辑重构为一个内部方法并从两个服务中调用它。但是,由于ServiceA依赖于接口IServiceB,因此不会公开内部方法。

你会如何处理这个问题?

更多信息(根据要求添加示例代码):

// This is the domain model
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// This is a dto for the domain model
public class CustomerDto
{
    public string Name { get; set; }
}

// Interface for ServiceA
public interface IServiceA
{
    void AddCustomer();
}

// ServiceA
public class ServiceA : IServiceA
{
    private readonly IServiceB _serviceB;

    // ServiceA takes in an IServiceB as a dependency
    public ServiceA(IServiceB serviceB)
    {
        _serviceB = serviceB;
    }

    public void AddCustomer()
    {
        var entity = new Customer();

        // !! This is the key part !!

        // I have to map to a dto in order to call the method on ServiceB.
        // This is a VERY simple example but this unnecessary mapping 
        // keeps cropping up throughout the service layer whenever
        // I want to make calls between services.

        var dto = Mapper.CreateFrom<CustomerDto>(entity);

        _serviceB.DoSomethingElseWithACustomer(dto);
    }
}

// Interface for ServiceB
public interface IServiceB
{
    void DoSomethingElseWithACustomer(CustomerDto customer);
}

// ServiceB
public class ServiceB : IServiceB
{
    public void DoSomethingElseWithACustomer(CustomerDto customer)
    {
        // Some logic here
    }
}
Run Code Online (Sandbox Code Playgroud)

odd*_*ity 2

关于到 DTO 的不必要映射:如果您更喜欢使用域驱动设计来访问数据库,请考虑使用数据访问对象或存储库。因此,您可以在服务层下面有一种“实用层”,直接与映射(实体)对象一起工作。

关于耦合类型:ServiceB可以实现多个接口,尤其是仅在服务器端可见的接口。ServiceA可以依赖该接口来访问更多ServiceB不适合发布到客户端的内部部分。