假设我的服务层中有两个服务,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
}
}