I am delving into domain events and need some advice about persisting updates to an entity for history reasons. My example deals with a User entity and Signing In:
public class UserService
{
private UserRepository _repository;
public UserService()
{
_repository = new UserRepository();
}
public User SignIn(string username, string password)
{
var user = _repository.FindByUsernameAndPassword(username, password);
//As long as the found object is valid and an exception has not been thrown we can raise the event.
user.LastLoginDate = DateTime.Now;
user.SignIn();
return user;
}
}
public class User
{
public User(IEntityContract entityContract)
{
if (!entityContract.IsValid)
{
throw new EntityContractException;
}
}
public Guid Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public DateTime LastLoginDate { get; set; }
public void SignIn()
{
DomainEvent.Raise(new UserSignInEvent() {User = this});
}
}
public class UserSignInEvent : IDomainEvent
{
public User User { get; set; }
}
public class UserSignInHandler : Handles<UserSignInEvent>
{
public void Handle(UserSignInEvent arguments)
{
//do the stuff
}
}
So where I have the do the stuff, I want to update the User object LastLoginDate and possibly log the date and time the user logged in for historical reasons. My question is, would I create a new instance of my repository and context to save the changes in the handler or pass something into the Event? This is what I am struggling with right now.