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?
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.
There are three types of dependency injection — constructor injection, method injection, and property injection.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With