Home > database >  UserControl with dependency injection Failed to create component
UserControl with dependency injection Failed to create component

Time:05-02

I have winform application I am trying to add a UserControl to my form but I get this error enter image description here

this is my UserControl

private readonly UserService userService;
private readonly UserValidator userValidator;
public UCUsers(UserService userService,UserValidator userValidator)
{
    InitializeComponent();
    this.userService = userService;
    this.userValidator = userValidator;
}

but when I create a constractor without using dependency injection it works fine.
How can I use a UserControl with dependency injection.

CodePudding user response:

Designer needs to generate code for your control; then how can it generate a line of code for instantiating your control? What parameters should it pass to the constructor?

#region Windows Form Designer generated code
/// <summary>
///  Required method for Designer support - do not modify
///  the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
    ...
    this.uCUsers1 = new UCUsers (??????, ??????);
    ...    

You need to create a parameterless constructor for your UserControl and define some properties for those kind of dependencies. Then at design-time you can use your control, and also at run-time you can set those dependencies, by resolving them through constructor of your form (or directly resolving through the service container).

For example, your user control should be something like this:

public class MyUserControl: UserControl
{
    public MyUserControl()
    {
        //...
    }
    public IHelloService HelloServiceInstance{get; set;}
    private void button1_Click(object sender, EventArgs e)
    {
        if(HelloServiceInstance!=null)
            MessageBox.Show(HelloServiceInstance.SayHello());
    }
}

Then at run-time, for example in OnLoad method or Load event handler or constructor of your form, just resolve the service and set the HelloServiceInstance property of the user control:

public Form1(IHelloService helloService)
{
    InitializeComponent();
    myUserControl1.HelloServiceInstance = helloService;
}
  • Related