I am trying to model a simple domain by using DDD. Database layer is implemented by using Entity Framework and domain objects are POCO. Domain has User entity which has FirstName, LastName and Username properties. Accordingly, domain defines IRepository that handles repository for users.
Now one requirement in the domain logic is that no two users with same username can exist. So trying to add new user when another one with the same username already exist should throw an exception.
IUnitOfWork unitOfWork = new UnitOfWork();
IRepository<User> users = unitOfWork.Users;
User user1 = new User() { Username = "jsmith", FirstName = "John", LastName = "Smith" };
users.Add(user1);
users.Save(); // ok, new user added to the underlying database
User user2 = new User() { Username = "jsmith", FirstName = "Jim", LastName = "Smith" };
users.Add(user2); // exception here?
users.Save(); // or exception here?
This is an example of the code that should go into the WPF application that adds new user. Here, UnitOfWork encapsulates Entity Framework’s DbContext object.
My question is how and where should I enforce this domain rule? Should exception be thrown when trying to add user into repository or rather when Save() method is called? Should I maybe create Domain Service for adding new users and then handle all domain logic rules there?
Also, what exception should I throw? Should I create some custom domain exception such as DuplicateUserException or something like that?
The db is the ultimate enforcer of that rule. Now, is this a multi user app? If so, then the most pragmatic way is to rely on the db , catch the sql exception and then throw a businessrule exception that will be redirected to the UI (i.e will trigger an error message).
You could verify that a name already exists at the domain level (via a Service is the most efficient way) but this can fail in a concurrent environment. However, it is an elegant and clean solution for a single user app. And by single user app I mean that ALL the app will serve one user at a time. If you have a WPF client and a web service, that’s a multi user app.
Your best bet is to let the persistence (in this case the db) handle this rule, because it’s the repo’s responsibility to ensure that there are no duplicate names (the repository is not a dumb bucket, it’s the manager of persistence) and it solves the concurrency problem as well.
Note that I haven’t mentioned EF, because it doesn’t matter the way you communicate with the db. If tomorrow you’ll switch to Azure db, the solution is still the same, only specific parts of implementation will be different.