Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get dependencies injected in constructors in Windows Forms

in asp.net-mvc I have the Windsor Controller Factory that injects all the dependencies into the controllers, but how do you get this in Windows Forms ?

for example if have this Form1, how am I going to get an instance of Form1, should I use resolve (which is called ServiceLocator and anti-pattern by some ppl)?

public class Form1
{
   private IBarService _barService;

   public Form1(IBarService barService)
   {
       _barService = barService;
   }
}
like image 543
Omu Avatar asked Feb 05 '10 19:02

Omu


1 Answers

Using Constructor Injection for Forms (or other Views in other UI frameworks) is often problematic because the Visual Studio designer expects and assumes a default constructor.

In any case, a Form or other visual Control really ought to be a dumb View without behavior. It's purpose is to display whatever data you bind to it. Using the data binding features often helps in constraining you into this passive form of display.

This means that you need some sort of Controller which can instantiate the View (Form) and bind the data source to it.

This is a lot easier to do with a technology such as WPF, but it's also possible with Windows Forms. For inspiration on how to do this with Windows Forms, I suggest that you take a look at the (now retired) Composite Application Block - it's overly complicated, but it should give you some ideas on how to implement something similar yourself.

like image 66
Mark Seemann Avatar answered Oct 15 '22 05:10

Mark Seemann