* Preface: I’m pretty new to the unit of work pattern *
My goal is to implement a unit of work class that will be able to keep track of all objects that have been changed throughout a given transaction. Everything I read about the unit of work pattern has it side by side with the repository pattern. So this is the approach I’d like to use.
Say for example I create a new User. On my unit of work object, I have a list of newly created objects, so I add my new User to this list. My user repository has a method titled Create, which takes in a User and calls a stored procedure to add the data to the database. When I call commit on my unit of work, how will it know which repository and method to call based on the list of new objects? Say it contains a User object and a Comment object. Both are newly created and need to be added on commit. I’m uncertain how to accomplish this.
Could somebody explain this a bit better and maybe even a small example if possible?
Thanks.
One of most common ways of solving this is using inversion of control.
For example, you’ve your classes User and Comment, and you’ve implemented a generic repository
IRepository<TDomainObject>. That’s getting a repository of User or Comment is just giving the TDomainObject parameter:IRepository<User>IRepository<Comment>Later you’ve configured who’s implementing
IRepository<User>andIRepository<Comment>, so if you use something like Microsoft Pattern & Practices’ Common Service Locator, and we’re in the body of commit method in your unit of work:Note
IRepository<TDomainObject>has a contravariant TDomainObject generic parameter which type must inherit a base type of Domain Object called DomainObject, which permits an upcast of something likeIRepository<User>toIRepository<DomainObject>.In other words, your
IRepository<TDomainObject>interface signature will look like this:This is just a summary and/or hint about how to implement locating the concrete repository so an unit of work of domain objects can manage ones of any specialized domain object.
If you want to learn more about inversion of control check this Wikipedia article:
And, because of my own experience, I’d like to suggest you Castle Windsor as inversion of control framework of choice: