I have to create a small app that uses windows forms. I want to use Simple Injector as IoC Container.
Documentation of Simple Injector wrote:
It is not possible to use Constructor Injection in User Controls. User Controls are required to have a default constructor. Instead, pass on dependencies to your User Controls using Property Injection.
I have followed the instructions, and my Program looks like this:
internal static class Program
{
[STAThread]
private static void Main()
{
App.EnableVisualStyles();
App.SetCompatibleTextRenderingDefault(false);
App.Run(Bootstrap().GetInstance<FormMain>());
}
private static Container Bootstrap()
{
var container = new Container();
container.Options.PropertySelectionBehavior =
new ImportPropertySelectionBehavior();
ConfigureServices(container);
AutoRegisterWindowsForms<Form>(container);
AutoRegisterWindowsForms<UserControl>(container);
container.Verify();
return container;
}
private static void ConfigureServices(Container container)
{
container.RegisterSingleton<IFormOpener, FormOpener>();
container.RegisterSingleton<IUserService, UserService>();
container.RegisterSingleton<IDatabaseService, DatabaseService>();
}
private static void AutoRegisterWindowsForms<T>(Container container)
where T: ContainerControl
{
var types = container.GetTypesToRegister<T>(typeof(Program).Assembly);
foreach (var type in types)
{
var registration =
Lifestyle.Transient.CreateRegistration(type, container);
registration.SuppressDiagnosticWarning(
DiagnosticType.DisposableTransientComponent,
"Forms should be disposed by app code; not by the container.");
container.AddRegistration(type, registration);
}
}
My problem is when using drag and drop to design UI, the user control is automatically generated using the new
operator, and property injection doesn't work. I don't want to inject the container directly into the form to GetInstance of the user control, because it is an anti-pattern, and the form design won't work either. Is there any way to solve this problem? Thank you everyone
EDIT I solved the problem my way. I have created a static class that contains the GetService method as follows:
public static class ServiceFactory
{
public static Container container;
public static TService GetService<TService>() where TService: class
{
return container.GetInstance<TService>();
}
}
The container needs to be assigned a value at program initialization:
private static Container Bootstrap()
{
var container = new Container();
ServiceFactory.container = container;
ConfigureServices(container);
AutoRegisterWindowsForms<Form>(container);
AutoRegisterWindowsForms<UserControl>(container);
container.Verify();
return container;
}
And I inject the service into the user control as follows:
private readonly IDatabaseService _databaseService;
public CustomUserControl()
{
InitializeComponent();
_databaseService = ServiceFactory.GetService<IDatabaseService>();
}