I’ve been studying DDD and I’m currently struggling to find a way to apply the concepts in actual code. I have about 10 years of experience with N-tier, so it’s very likely that the reason I’m struggling is that my mental model is too coupled to that design.
I’ve created an Asp.NET Web Application and I’m starting with a simple domain: a web monitoring application. Requirements:
- The user must be able to register a new Web App to monitor. The web app has a friendly name and points to a URL;
- The web app will periodically poll for a status (online/offline);
- The web app will periodically poll for its current version (the web app is expected to have a “/version.html”, which is a file declaring its system version in a specific markup).
My doubts concern mainly the division of responsibilities, finding the proper place for each thing (validation, business rule, etc). Below, I’ve written some code and added comments with questions and considerations.
Please criticize and advise. Thanks in advance!
DOMAIN MODEL
Modeled to encapsulate all business rules.
// 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(). } }
And a DomainService class to handle Creates and Deletes, which I believe are not the concern of the Aggregate itself.
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; } }
APPLICATION LAYER
The class below provides an interface for the WebMonitoring domain to the outside world (web interfaces, rest api’s, etc). It’s just a shell at this moment, redirecting calls to the appropriate services, but it would grow in the future to orchestrate more logic (accomplished always via domain models).
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); } }