私はDDDを研究しており、現在、実際のコードに概念を適用する方法を見つけるのに苦労しています。私はN層で約10年の経験があるので、私が苦労している理由は、私のメンタルモデルがそのデザインにあまりにも結合しているためです。
私はAsp.NET Webアプリケーションを作成し、単純なドメインであるWeb監視アプリケーションから始めています。要件:
- ユーザーは、監視する新しいWebアプリを登録できる必要があります。Webアプリにはわかりやすい名前が付けられ、URLをポイントします。
- Webアプリは定期的にステータス(オンライン/オフライン)をポーリングします。
- Webアプリは定期的に現在のバージョンをポーリングします(Webアプリには、特定のマークアップでシステムバージョンを宣言するファイルである「/version.html」が含まれていることが予想されます)。
私の疑問は主に責任の分割に関係しており、それぞれの適切な場所(検証、ビジネスルールなど)を見つけることです。以下に、コードをいくつか書き、質問と考慮事項を含むコメントを追加しました。
批判し、助言してください。前もって感謝します!
ドメインモデル
すべてのビジネスルールをカプセル化するようにモデル化されています。
// Encapsulates logic for creating and validating Url's.
// Based on "Unbreakable Domain Models", YouTube talk from Mathias Verraes
// See https://youtu.be/ZJ63ltuwMaE
public class Url: ValueObject
{
private System.Uri _uri;
public string Url => _uri.ToString();
public Url(string url)
{
_uri = new Uri(url, UriKind.Absolute); // Fails for a malformed URL.
}
}
// Base class for all Aggregates (root or not).
public abstract class Aggregate
{
public Guid Id { get; protected set; } = Guid.NewGuid();
public DateTime CreatedAt { get; protected set; } = DateTime.UtcNow;
}
public class WebApp: Aggregate
{
public string Name { get; private set; }
public Url Url { get; private set; }
public string Version { get; private set; }
public DateTime? VersionLatestCheck { get; private set; }
public bool IsAlive { get; private set; }
public DateTime? IsAliveLatestCheck { get; private set; }
public WebApp(Guid id, string name, Url url)
{
if (/* some business validation fails */)
throw new InvalidWebAppException(); // Custom exception.
Id = id;
Name = name;
Url = url;
}
public void UpdateVersion()
{
// Delegates the plumbing of HTTP requests and markup-parsing to infrastructure.
var versionChecker = Container.Get<IVersionChecker>();
var version = versionChecker.GetCurrentVersion(this.Url);
if (version != this.Version)
{
var evt = new WebAppVersionUpdated(
this.Id,
this.Name,
this.Version /* old version */,
version /* new version */);
this.Version = version;
this.VersionLatestCheck = DateTime.UtcNow;
// Now this eems very, very wrong!
var repository = Container.Get<IWebAppRepository>();
var updateResult = repository.Update(this);
if (!updateResult.OK) throw new Exception(updateResult.Errors.ToString());
_eventDispatcher.Publish(evt);
}
/*
* I feel that the aggregate should be responsible for checking and updating its
* version, but it seems very wrong to access a Global Container and create the
* necessary instances this way. Dependency injection should occur via the
* constructor, and making the aggregate depend on infrastructure also seems wrong.
*
* But if I move such methods to WebAppService, I'm making the aggregate
* anaemic; It will become just a simple bag of getters and setters.
*
* Please advise.
*/
}
public void UpdateIsAlive()
{
// Code very similar to UpdateVersion().
}
}
そして、CreatesとDeletesを処理するDomainServiceクラス。これはAggregate自体の問題ではないと私は思います。
public class WebAppService
{
private readonly IWebAppRepository _repository;
private readonly IUnitOfWork _unitOfWork;
private readonly IEventDispatcher _eventDispatcher;
public WebAppService(
IWebAppRepository repository,
IUnitOfWork unitOfWork,
IEventDispatcher eventDispatcher
) {
_repository = repository;
_unitOfWork = unitOfWork;
_eventDispatcher = eventDispatcher;
}
public OperationResult RegisterWebApp(NewWebAppDto newWebApp)
{
var webApp = new WebApp(newWebApp);
var addResult = _repository.Add(webApp);
if (!addResult.OK) return addResult.Errors;
var commitResult = _unitOfWork.Commit();
if (!commitResult.OK) return commitResult.Errors;
_eventDispatcher.Publish(new WebAppRegistered(webApp.Id, webApp.Name, webApp.Url);
return OperationResult.Success;
}
public OperationResult RemoveWebApp(Guid webAppId)
{
var removeResult = _repository.Remove(webAppId);
if (!removeResult) return removeResult.Errors;
_eventDispatcher.Publish(new WebAppRemoved(webAppId);
return OperationResult.Success;
}
}
アプリケーション層
以下のクラスは、WebMonitoringドメインの外部へのインターフェースを提供します(Webインターフェース、REST APIなど)。これは現時点では単なるシェルであり、適切なサービスへの呼び出しをリダイレクトしますが、将来的にはより多くのロジックを調整するように成長するでしょう(常にドメインモデルを介して実現されます)。
public class WebMonitoringAppService
{
private readonly IWebAppQueries _webAppQueries;
private readonly WebAppService _webAppService;
/*
* I'm not exactly reaching for CQRS here, but I like the idea of having a
* separate class for handling queries right from the beginning, since it will
* help me fine-tune them as needed, and always keep a clean separation between
* crud-like queries (needed for domain business rules) and the ones for serving
* the outside-world.
*/
public WebMonitoringAppService(
IWebAppQueries webAppQueries,
WebAppService webAppService
) {
_webAppQueries = webAppQueries;
_webAppService = webAppService;
}
public WebAppDetailsDto GetDetails(Guid webAppId)
{
return _webAppQueries.GetDetails(webAppId);
}
public List<WebAppDetailsDto> ListWebApps()
{
return _webAppQueries.ListWebApps(webAppId);
}
public OperationResult RegisterWebApp(NewWebAppDto newWebApp)
{
return _webAppService.RegisterWebApp(newWebApp);
}
public OperationResult RemoveWebApp(Guid webAppId)
{
return _webAppService.RemoveWebApp(newWebApp);
}
}
問題を閉じる
ここと別の理由で開いたこの他の質問で回答を集めた後、最終的にこれと同じポイントに到達し、このよりクリーンでより良い解決策を思いつきました: