UnitOfWork lifespan in WPF with an IoC Container
Asked Answered
F

1

13

My basic setup is a lot like this; http://visualstudiomagazine.com/articles/2011/10/01/wpf-and-inversion-of-control.aspx

An MVVM setup in WPF. I'm injecting a UnitOfWork and a RepositoryFactory into the ViewModel. This has worked great for the dialogs I've written so far... However large portions of our application are inside of dockable windows (think Visual Studio UI). These are open for as long as the application is.

So my thought is to move the unitofwork from being the lifetime of a dialog down to the lifetime of a method call (Button.Click() for example).

But I haven't figured out a good way of doing that which doesn't break some of the benefits I get from using Castle Windsor as an IoC container and/or not following DRY.

This seems pretty good... http://www.codeproject.com/Articles/543810/Dependency-Injection-and-Unit-Of-Work-using-Castle But I worry about the session being wrapped in a semi-singleton and worry that I might be shooting myself in the foot by removing direct access to the UnitOfWork.

Anyone have a good solution for this? Is the above codeproject good and if not what are its flaws?

Foppish answered 1/5, 2013 at 20:6 Comment(6)
Hello Fenyx, I tend not to use an explicit using of work, but rather use ISession (NHibernate) or DbContext (EF) directly. The lifetime for these are bound to the viewmodels even if they have an application lifespan. As long as these views don't accumulate more and more data from the database I don't see a problem. Keep in mind that a DbContext/ISession is not the same as a Database connection.Toxemia
Without too much talking, check out this [question][1]. [1]: #3653509Goldstein
@Sniffer that's [link caption](url) ;)Mentholated
@retailcoder That's 5 months old. I know that now, but Thank you.Goldstein
If you are worried about the lifetime of a component you could instead inject in a factory responcible for creating an instance of the component. A reference to the factory would be kept in the viewmodel and on each click/event/command a new instance of the component could be created, used and then destroyed.Heathen
The code project article you linked seems like it would work, but I think it's overkill. I'm not a huge fan of the UnitOfWork being applied to the an entire method. It's not very flexible and seems like it would get annoying. You say you're injecting a UnitOfWork and a RepositoryFactory. Instead of having one long-living UnitOfWork why not inject a UnitOfWork Factory? It seems like you should be able to start a UnitOfWork at will and that it shouldn't be tied to its parent's lifespan.Thalassography
C
3

Just introduce Unit Of Work Factory (for example, IUnitOfWorkFactory) interface and use it where appropriate (inject it, etc).

Also, consider making IUnitOfWork interface inherited from IDisposable interface.

Chester answered 28/1, 2015 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.