Proper Repository Design, Attaching one Object to Another
In my attempt to keep with a good Repository/IoC Design, I am trying to figure out the best approach the current problem.
There are two objects, Member
, and Character
.
Basically, one Member can have many characters. Simple enough.
Member
{
IList<Character> Characters { get; set; }
}
There is an IMemberRepository
...
interface IMemberRepository
{
MemberCreateStatus CreateMember(开发者_运维问答string email, string password);
bool ValidateMember(string email, string password);
bool ChangePassword(string email, string password, string newPassword);
void RecoverPassword(string email);
}
And there is an ICharacterRepository
interface ICharacterRepository
{
Character CreateCharacter(string name);
}
So then, my question is quite simple. Where do I want to add the logic to add a Character
to a Member
? Do I do this in IMemberRepository
? That seems cumbersome to me. It seems beyond the scope of the IMemberRepository
's tasks. Do I add it to the ICharacterRepository
? That too seems a bit strange to me, because giving that knowledge of the Membership seems to be in violation of keeping them separated. What's the best approach to take, here?
If it were just this one method, it wouldn't be too big a deal - but there will be a lot of other things that have to occur between the two classes. What's the 'standards' way to approach this situation of two objects relating to one another? I am coding this in ASP.NET MVC.
I think you are maybe approaching Repositories a little differently than intended, and that may be the cause of some of your confusion.
Repositories are to provide collection semantics to a set of data. That means Repositories Get, Add, and Remove stuff. They don't validate. They don't change things about individual items. They are not a Data Access Object (DAO), though it seems many people lately name a thing Repository and then make it look like a DAO.
Your Member contains a list of Characters. Great! Want to add a Character to a Member? Do exactly that. Member.AddCharacter(...)
or Member.Characters.Add(...)
. I usually use the former, but the latter can work as well (but requires custom collection implementations).
I feel it is responsibility of IMemberRepository
to populate Characters
of a Member
. There are a few reasons:
- Since
IMemberRepository
isMember
type'sRepository
, it knows whatMember
is composed of. And that is why it knows aboutCharacter
type. - It is certainly not
ICharacterRepository
's responsibility.Character
type can be used to compose other types in future. That will affectCharacter
'sRepository
whenever you add new type. IMemberRepository
will be usingICharacterRepository
to populateCharacter
objects inMember
.
The most natural approach for me is to put that logic inside the Member class as the Member object is responsible of tracking its own Characters.
What do you think about that?
精彩评论