IoC and user interfaces

I'm trying to get my head around the best way to use IoC in my dependency injection application, however, I have a little problem.

I am using a free implementation of the MVP pattern with a WPF application. Essentially, the presenter class is instantiated and the view and task (such as IEmployeeView and IEmployeeTask for EmployeePresenter) are injected into the presentation.

I would like to use an IoC container (I am trying to merge Unity, although I suppose this will also happen with others like ninject or Structure Map) instead of manually injecting these instances, however if the creator is created (or resolved from the IoC container ) when invoking an async delegate or event thread (e.g. not on an STA thread), then creating a new instance of the WPF window throws the following exception:

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

Now I know that new instances of windows, etc. should be STA, however is it possible to use an IoC container for dependency injection even when the UI needs to be created on an STA thread?

From looking at this issue, it seems that the resolved class / type is created at the time of resolution, not when it is registered ...

0


source to share


3 answers


I would say to use Factory to create Presenter objects; This way you can create your generic presenter instances from your PresenterFactory on the STA thread and then just pass them around as needed.



+2


source


Your problem has nothing to do with IoC, the WPF object can only be accessed from the same thread that created it, so you need to create your master on the same thread as your entire GUI (not just any STA thread).



Use Dispatcher.BeginInvoke to run the code on the main thread and call Ioc contianer.

+2


source


You mention Unity, have you looked at using a composite application library that also uses it? SampleTrader uses Unity to enter views in presentation models. If you don't want to use CAL - more information: ( http://msdn.microsoft.com/en-us/library/cc707890.aspx or http://www.codeplex.com/CompositeWPF )

you can still decide how they dealt with the problem.

+2


source







All Articles