views:

284

answers:

3

I'm trying to wrap my head around the best way to use IoC within my application for dependency injection, however I have a little issue.

I am using a loose implementation of the MVP pattern with a WPF app. Essentially, a presenter class is instantiated, and a view and task (e.g. IEmployeeView and IEmployeeTask for EmployeePresenter) are injected into the presenter.

I would like to use an IoC container (I'm trying out Unity, though I guess this would also happen with others such as ninject or Structure Map) instead of manually injecting these instances, however if the presenter is created (or resolved from an IoC container) on an async delegate call, or an event thread (e.g. not STA threaded) then creating a new instance of a WPF window throws the following exception:

The current build operation (build key Build Key[namespace.Window1, null]) failed: The calling thread must be STA, because many UI components require this.

Now, I know that new window instances etc need to be STA, however is it possible to use an IoC Container to do the dependency injection even when the UI must be created on an STA thread?

From looking at this problem it would seem that the class/type being resolved is instantiated at the resolve time, not when its registered...

+1  A: 

I would say to use a Factory to create the Presenter objects; that way, you can create your generic instances of Presenters from within your PresenterFactory in an STA thread, and then simply pass them out when required.

McWafflestix
+1  A: 

Your problem have nothing to do with IoC, a WPF object can only be accessed from the same thread that created it - so you have to create your presenter on the same thread as the rest of your GUI (and not just any STA thread).

Use Dispatcher.BeginInvoke to run code in the main thread and call Ioc contianer from there.

Nir
This is the most probable cause, IoC containers work fine in WPF.
Jab
+1  A: 

You mention Unity, have you looked at using the Composite Application Library which also uses it? The StockTrader sample application uses Unity to inject views to presentation models.. If you don't want to actually use the CAL - more info: (http://msdn.microsoft.com/en-us/library/cc707890.aspx or http://www.codeplex.com/CompositeWPF)

you might still be able to work out how they got around the issue..

Trev