I am using Unity DI in a windows forms application. It is working so far resolving dependencies to the main form in program.cs like this:
static void Main()
{
IUnityContainer container = new UnityContainer();
container.AddNewExtensionIfNotPresent<EnterpriseLibraryCoreExtension>();
container.RegisterType<IAccountService, AccountService>();
container.RegisterType<IAccountRepository, AccountRepository>();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(container.Resolve <MainForm>());
}
My problem is when my MainForm tries creates a child form:
ChildForm childForm = new ChildForm();
childForm.Show();
I am getting an error because I’m trying to use constructor injection and I’m not passing in the constructor arguments. I also tried using setter injection with the [Dependency] attribute but that didn’t work either. How should I accomplish this? I could have my main form have all the dependencies and pass the required objects to the child forms, but if I end up having many child forms then the main form would be messy.
In order for Unity to inject the constructor arguments, you’ll need to use the container to resolve the child form. So you’ll need to hold a reference to your container somewhere, then call:
This will allow Unity to evaluate the ChildForm constructors and inject the appropriate dependencies.