Jan 18, 2011 at 7:22 PM
Edited Jan 19, 2011 at 2:36 AM
i'm a bit of a newbie when it comes to injection and unity container. i have been trying out some of the things related to unity and mvc trying understand how to integrate it into a windows application and i came across a problem..
I have implemented two forms using the mvc pattern. my requirement is to open one form (Form1) initially via Program.cs and after a button has been pressed on that open up the other form (Form2). I have no problem opening 'Form1' using
the unity container, the problem comes when i try to open the other form, becos i have no way of accessing the Unity container used to open up 'Form1', I can always define a new unity container in 'Form1' and try to open 'Form2', but this defies the purpose
of injection as i have to register all the types again.
Am i missing something????
i did some research and found out that some ppl hav injected the container into the form (via property injection). But i'm not sure if this is the way to go....
please keep in mind this is a windows application, so i had to manually implement the mvc pattern (unlike in web apps),
please let me know if you need any additional information.
Thnks in Advance
You should do neither.
The container should only be touched in a very, very small subset of your code, ideally only in the startup of your application. If you need to resolve stuff out of the container later, you should encapsulate this into a factory service, then inject the
There are a couple of approaches you can use.
First, just use new. Have the things that Form2 needs injected into Form1 and passed along when it constructs it.
Second, like I said, define an explicit "IForm2Factory" service, which gets injected into Form1. Then inside the implementation of the factory, you can get the container injected. This way your still insulating your main logic from the presence
of a container.
Third, If you were were just going to call container.Resolve<Form2>(), then you can skip the explicit factory. Instead, specify a dependency in Form1 of type Func<Form2>. This'll inject a delegate into Form1 that, when called, will call back
into the container. We've been calling this an automatic factory.
Hope this helps,