I have a Unity DI container that works first with my Windows Forms application. In Program.cs , I have the following:
static void Main() { var container = BuildUnityContainer(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(container.Resolve<MainForm>()); } private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<ITest, MyTestClass>(); container.RegisterType<ISomeOtherTest, MyOtherClass>(); return container; }
In my MainForm constructor, I have the following that works :
private readonly ITest test; public MainForm(ITest test) { this.test = test; InitializeComponent(); }
The container is enabled and the code is working fine. Problem / question: how can I create a new form from MainForm , say Form2 , which has the following constructor:
private readonly ISomeOtherTest someOtherTest; public Form2(ISomeOtherTest someOtherTest) { this.someOtherTest = someOtherTest; InitializeComponent(); }
If I try the following in MainForm :
Form2 form2 = new Form2(); form2.Show();
It will break, complaining that I did not pass the meaning to the constructor. However, I already allowed my container, and I thought that all subsequent containers would be allowed. Obviously, I missed something, although this does not work.
Does this mean that I should before loading all the dependencies in MainForm , even if this form does not use it, so I can pass them to any new instances of the form that I create? It would be strange if I had 50 dependencies to allow and that the constructor for the top-level form would take them all. Please help to understand my understanding, since I used Unity and DI containers almost exclusively in web APIs and MVCs, which already have a DI resolver built-in for controllers, so I have to miss some parts and understand here.