i'm struggling a bit with repositories. I'm using C# and NHibernate. The question i have is : how much should my repository do before it calls a save or a get?
For example i have a user class which is an aggregate root. I want to call a method called "register" which will add the user and set some default values based on business rules and create some other entities which are also sub parts of the "user" root (ie address, groups, etc) . Should i call
userRepo.Register(newUser);
which would be(ignoring the obvious issues):
Regsiter(User newUser){
newUser.SomeProp = "Default Data";
Group g= new Group;
g.SomeProp2 = "Default Data";
newUser.Groups.Add(g);
Session.Save(g);
Session.Save(newUser);
}
or should i have put register in a business layer and have it do:
Regsiter(User newUser){
newUser.SomeProp = "Default Data";
Group g= new Group;
g.SomeProp2 = "Default Data";
newUser.Groups.Add(g);
userRepo.Register(newUser, g);// this does session.save on both objects.
}
Both seems slightly wrong.
What's the correct approach?
edit -------------------------------
thanks for all the responses. I can't decide who is the most right and therefore which answer to accept.
Generally everyone is saying put the business rules in another layer. that makes sense but i'm unsure about the data calls for groups - since groups aren't an aggregate root they shouldn't have their own repository so how do i go about adding and saving them? In my project adding a group to the user's group collection doesn't automatically create the group in the db; i also need to call session.save on the object. so do i put that into the user repo as userRepo.SaveGroup(g)?
If i have a createGroup() in the other layer then it'll either need to use it's own repo or the users. or am i being thick?
Personally, I keep the repository pattern as a substitute for sprocs. So my repository would have methods like getById(int id)
, save()
, add(DomainObject obj)
etc.
In a business tier, I'd have userManager.registerUser(string username, /* params, etc */). This would create the domain object. This method would just call the add()
method in the data tier.
In short, the business tier is business-y, and the data tier is data-y.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With