R – IoC and User Interfaces

dependency-injectioninversion-of-controlstawpf

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…

Best Answer

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.