假设我的服务层中有两个服务,分别为ServiceA
和ServiceB
,每个服务都有一个接口(分别为IServiceA
和IServiceB
)。DTO和服务之间的呼叫
UI层仅引用服务接口,从其方法返回DTOs。具体的服务类负责将域模型(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
}
}
请问您可以添加一些代码(无需实际处理),以便更容易理解您的用例和当前体系结构? –
根据要求添加示例。我试图将其降至最低限度,以突出显示实际问题案例之一。返回值等会出现同样的问题。 –
我是否正确理解以这种方式您有两个生成的文件,其中定义了CustomerDto(我不计算您的DTO项目声明) - 在ServiceA和ServiceB的命名空间中,尽管存在此声明是平等的 - 他们是不同的实体。你正在寻找一种解决方法吗? –