![](/img/trans.png)
[英]Should handler from the Application layer return DTO or domain object
[英]Should the domain layer receive a dependency DTO directly?
這可能以前曾被問過,但是我正在數據訪問層中訪問依賴項Web服務,我需要問是否應該將從該服務返回的DTO重新包裝到我自己的DTO中? UI層是帶有控制器的WebAPI項目,而域和數據訪問層是單獨的C#項目。 在每一層中引用依賴項Web服務是否正確,以便dal,biz和domain層都具有適當的代碼引用,還是我應該為從DAL層中的Web服務返回的DTO創建我自己的視圖?
從DDD的角度來看,我每次都以類似的方式執行此操作。 我傾向於在經典的分層體系結構上使用端口和適配器類型的體系結構。 主要是因為它允許我通過IoC連接的接口輕松引用我的持久層。 這幾乎提供了兩種方式的參考,在這里我不僅可以從域訪問我的持久層,而且可以在持久層中使用域模型。
訪問外部Web服務時,我所做的工作非常相似。 我設置了一個新的適配器,並將用於訪問外部服務的接口放在我的域中,然后使用IoC進行了連接。 然后,我可以使用通常在我方(客戶端)上自動生成(或手工生成)的某些DTO來訪問外部Web服務,然后將它們映射到我的域對象。
例如,在一個我正在進行地理編碼(將郵政編碼查找為坐標)的項目中,在我的域模型中一個名為Geographical的文件夾中,我有一個名為IGeocodingService的接口:
namespace Booking.Domain.Model.Geographical
{
/// <summary>
/// The <see cref="IGeocodingService" /> interface.
/// </summary>
public interface IGeocodingService
{
/// <summary>
/// Performs a postal code query.
/// </summary>
/// <param name="countryIsoCode">The country iso code.</param>
/// <param name="postalCode">The postal code.</param>
/// <returns>A geographic coordinate.</returns>
Coordinate PostalCodeQuery(string countryIsoCode, string postalCode);
}
}
在一個名為Booking.Adapter.CloudMade的單獨項目中,我有一個名為CloudMadeGeocodingService的服務,該服務繼承自IGeocodingService :
namespace Booking.Adapter.CloudMade
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Booking.Domain.Model.Geographical;
/// <summary>
/// The <see cref="CloudMadeAdapter" /> class.
/// </summary>
public class CloudMadeGeocodingService : IGeocodingService
{
/// <summary>
/// Performs a postal code query.
/// </summary>
/// <param name="countryIsoCode">The country iso code.</param>
/// <param name="postalCode">The postal code.</param>
/// <returns>
/// A geographic coordinate.
/// </returns>
public Coordinate PostalCodeQuery(string countryIsoCode, string postalCode)
{
string country;
switch (countryIsoCode)
{
case "GB":
country = "UK";
break;
default:
country = null;
break;
}
if (country == null)
{
return null;
}
using (HttpClient httpClient = new HttpClient())
{
// TODO: Make call to CloudMade v2 geocoding API.
}
// TODO: Remove this.
return null;
}
}
}
從我的領域的角度來看,以這種方式做事有2大優勢。 第一個是該服務將自身包裝為某種外部組件 ,第二個是它采用並返回本機C#.NET類型或我自己的域模型類型。 該實現是隱藏的,在這種情況下,如果需要的話,任何DTO都將隱藏(在此示例中,實際上沒有),並且數據來自Web API Web服務的事實也被隱藏了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.