views:

28

answers:

1

When I started with Windsor I thought DI would be simple. Now it's causing me more and more confusion.

A repository strikes me as a class with a singleton lifecycle. I should have a single instance of a FooRepository to load and save Foos to the database during the application's lifetime.

However, each repository holds a reference to a UnitOfWork, which does the dirty checking, works with the database etc. The UnitOfWork has a lifecycle of PerWebRequest - it makes no sense at all for the UnitOfWork to be a singleton, as a singleton instance could (for example) flush the changes made by several user sessions at the same time.

So then I have a singleton FooRepository holding a reference to a UnitOfWork, which at the end of the session gets disposed! I'm not even sure what effect that would have on the repository's behaviour, but it doesn't sound good.

Can anyone explain, in simple English (okay, maybe with some code), the appropriate way to manage the lifecycle of Repository and UnitOfWork classes in a web app?

A: 

Rule of thumb is - component should not depend on other components that will outlive it.

In other words, it's ok for transient to depend on singleton, or per-web-request component, but not the other way around.

The way I approach Repository - UoW scenario is my UoW is per web request, but repositories are stateless and transient.

Krzysztof Koźmic
Transient? Ah, interesting. But presumably using a PerWebRequest repository with a PerWebRequest UoW (as I'm currently doing) is also fine? (Seems to work for me, anyway.)
David
What do you mean by stateless? Do you mean they don't hold a reference to a UoW?
David
Oh, suggested edit - 'component should not depend on other components that it will outlive'. But I know what you meant, thanks!
David
stateless means it has not state of its own. It does keep reference to UoW
Krzysztof Koźmic