1

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>();
}

1 Answer 1

1

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.

This is exactly why the documentation refers to property injection. Property injection allows to be applied on externally created instances (as user controls are created by the UI framework, not the DI Container).

What the documentation fails to mention, however, is how to initialize a created instance with dependencies. Simple Injector contains an InitializeInstance for this. The following code allows initializing user controls that use explicit property injection:

private static Container container;

public static void InitializeControl(UserControl control)
{
    var producer = container.GetRegistration(control.GetType(), true);
    producer.Registration.InitializeInstance(control);
}

This, unfortunately, is far from perfect because it requires forms and user controls to depend on the DI Container. To prevent this, you can pass on dependencies from the containing form to the user control through Method Injection instead, but the downside of this is that you'd easily have to pass many dependencies, causing the consuming form's constructor to explode.

Alternatively, contrary to what the documentation states, it is possible to resolve user controls from the DI Container and circumvent using the designer as stated here by Ron. This might have consequences of its own, however, and I have no experience with this.

1
  • I solved the problem and edit my question. Please take a look and let me know your opinion. Thank you
    – Minh Giang
    Commented Jul 3, 2021 at 4:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.