Unity DI in Windows Forms with child forms
I am using Unity DI in a windows forms application. It works 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 method creates a child form:
ChildForm childForm = new ChildForm();
childForm.Show();
I am getting the error because I am trying to use constructor injection and I am not passing constructor arguments. I also tried using setter injection with the [Dependency] attribute, but that didn't work either. How am I supposed to do 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 with many child forms, the main form will be messy.
source to share
For Unity to inject constructor arguments, you will need to use a container to resolve the child form. So you will need to store a link to your container somewhere and then call:
ChildForm childForm = container.Resolve<ChildForm>();
This will allow Unity to evaluate the ChildForm constructors and inject the appropriate dependencies.
source to share
In the comment above, you mentioned "mak [ing] in the container public property program.cs".
Do not do this.
If your form has a container dependency, treat it like any other dependency.
- add the container to the container.
-
Use either property or ctor injection to give the form access to the container.
static void Main() { IUnityContainer container = new UnityContainer(); container .RegisterType<MainForm>() .RegisterInstance<IUnityContainer>(container);
...
public partial class MainForm: Form
{
[Dependency]
public IUnityContainer Container { get; set; }
source to share