Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods to use constructor injection in user controls?

Are there any ways to enforce or allow constructor required dependencies for a user control without breaking the designer? What work arounds exist?

a default constructor with EditorBrowsable.Never or property injection, but I prefer constructor injection.

other work-arounds or solutions?

like image 639
Maslow Avatar asked Feb 11 '11 14:02

Maslow


People also ask

What is the use of constructor injection?

Constructor Injection is the act of statically defining the list of required Dependencies by specifying them as parameters to the class's constructor. The constructor signature is compiled with the type and it's available for all to see.

Which methods are dependency injection?

There are three types of dependency injection — constructor injection, method injection, and property injection.

How is constructor injection implemented?

Constructor Injection Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.

What is a constructor injection?

Constructor Injection is the most common form of Dependency Injection. Constructor Injection is the act of statically defining the list of required dependencies by specifying them as parameters to the class's constructor.


2 Answers

You can overload constructors. The designer is going to require the default constructor at design time so be sure to supply that one as well.

    public UserControl1() {
        InitializeComponent();
    }
    public UserControl1(Foo arg) : this() {
        // Do something with arg
        //...
    }

Of course, the client code has to create that user control itself. Favor properties to keep the user control useful in the designer. Throw an exception in OnLoad() if DesignMode is false and you're not happy about the way the client code used your control.

like image 39
Hans Passant Avatar answered Sep 22 '22 14:09

Hans Passant


Design user controls so that they don't use dependencies.

Look at the controls (ASP.NET, Windows Forms, WPF, etc.) supplied by Microsoft. None of them use dependencies. Instead, you assign data to them - often by way of writable properties.

This is a more SOLID design because a control's single responsibility should be to render data. Thus, if you also give it the responsibility of retrieving or formatting data, you are breaking the Single Responsibility Principle.

When you design controls like that, a default constructor becomes natural.

like image 78
Mark Seemann Avatar answered Sep 20 '22 14:09

Mark Seemann