Skip to content

Instantly share code, notes, and snippets.

@phillippelevidad
Last active January 3, 2018 11:50
Show Gist options
  • Save phillippelevidad/a981edd0bcfef5ad3bda569b9ee2db17 to your computer and use it in GitHub Desktop.
Save phillippelevidad/a981edd0bcfef5ad3bda569b9ee2db17 to your computer and use it in GitHub Desktop.
Solution attempt for the Web Monitoring domain modeling.
/* File structure:
* /Domain/WebMonitoring/WebAppAggregate/WebApp.cs
* /Domain/WebMonitoring/WebAppAggregate/WebAppService.cs
* /Domain/WebMonitoring/WebAppAggregate/IWebAppRepository.cs
* /Domain/WebMonitoring/WebAppAggregate/IHttpStatusChecker.cs
*
* This way, the Aggregate itself is not "materialized" as a class or any programming resource.
* It is a concept, and its invariants are enforced by the WebApp (entity, aggregate root) and
* WebAppService.
*/
public class WebApp : Entity, IAggregateRoot
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public Url Url { get; private set; }
public bool IsAlive { get; private set; }
public WebApp(Guid id, string name, Url url)
{
// Validation goes here...
// If ok, set properties. Throw exception, otherwise.
this.AddDomainEvent(new WebAppRegisteredEvent(id, name, url));
Id = id;
name = name;
Url = url;
}
public void UpdateIsAlive(bool isAlive)
{
if (isAlive != this.IsAlive)
this.AddDomainEvent(new WebAppStatusChangedEvent(Id, oldStatus: IsAlive, newStatus: isAlive));
IsAlive = isAlive;
}
}
public class WebAppService
{
private readonly IWebAppRepository _repository;
private readonly IUnitOfWork _uow;
private readonly IHttpStatusChecker _httpStatusChecker;
public WebAppService(IWebAppRepository repository, IUnitOfWork uow, IHttpStatusChecker httpStatusChecker)
{
_repository = repository;
_httpStatusChecker = httpStatusChecker;
}
public Result RegisterWebApp(Guid id, string name, Url url)
{
var webApp = new WebApp(id, name, Url);
var addResult = _repository.Add(webApp);
if (!addResult.OK) return Result.Fail(addResult.Errors);
var commitResult = _uow.Commit();
if (!commitResult.OK) return Result.Fail(commitResult.Errors);
return Result.OK;
}
public Result UpdateWebAppStatus(Guid id)
{
var webApp = _repository.GetById(id);
if (webApp == null) return Result.Fail($"Web App '{id}' not found");
var status = _httpStatusChecker.GetStatus(webApp.Url);
var isAlive = (status == 200);
webApp.UpdateIsAlive(isAlive);
var updateResult = _repostory.Update(webApp);
if (!updateResult.OK) return Result.Fail(updateResult.Errors);
var commitResult = _uow.Commit();
if (!commitResult.OK) return Result.Fail(commitResult.Errors);
return Result.OK;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment