编程语言
首页 > 编程语言> > c# – DTO和服务之间的通话

c# – DTO和服务之间的通话

作者:互联网

假设我的服务层ServiceA和ServiceB中有两个服务,每个服务都有一个接口(分别是IServiceA和IServiceB).

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

ServiceA通过使用IoC容器的依赖注入来依赖IServiceB,以便在该服务上调用某些方法.

这样做会产生一些问题:

>与DTO之间的不必要/重复映射只是为了调用方法和/或使用结果.
>将调用方法与调用方法输入参数和返回类型的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
    }
}

解决方法:

关于对DTO的不必要映射:考虑使用Data Access ObjectsRepositories if you prefer Domain Driven Design访问数据库.因此,您可以在服务层下面使用一种“实用程序层”,直接使用映射(实体)对象.

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

标签:c,architecture,dto,service-layer
来源: https://codeday.me/bug/20190624/1283087.html