Working on a DDD application where I need to persist state. Here's a very simple example:
public interface IRoot {
public int Id { get; }
void UpdateValue(int value);
}
public interface IState {
int Id { get; }
int CurrentValue { get; }
}
public class AggregateRoot : IRoot {
private State _state;
internal AggregateRoot(State state){
_state = state;
}
public int Id { get { return _state.Id; } }
public void UpdateValue(int value){
_state.CurrentValue = value;
}
}
public class State : IState {
internal State(int id){
Id = id;
}
public int Id { get; internal set; }
public int CurrentValue { get; internal set; }
}
By using the internal setter / getter only interface, I can ensure that state isn't changed outside of the business logic implemented in the domain root. I have a factory/builder set up within the same project to instantiate new roots w/ state.
My problem comes when it comes to persisting / loading state from some data store. I'm trying to keep the persistence implementation details totally separate from the domain, so I create a repository interface for persisting the state:
public interface IStateRepository {
void Save(IState state);
void Delete(int key);
IState Get(int key);
}
Since I'm using interfaces without setters in the repository, I can't update the state ID on save, or populate an object directly. The IStateRepository implementation is in a completely separate project, so even id I changed repository to use the state directly, I still wouldn't have access to properties without using reflection.
The only solution I can think of that would still allow me to have clean separation is to implement a DTO that would act as mapping object between the domain and the persistence layers, but that doesn't feel right. I'd essentially be creating a duplicate object with the properties of the State object, but with public setters.
Surely there is some obvious pattern I'm missing?