DaveyBoy
DaveyBoy

Reputation: 435

Integrating Unity Container into existing WinForms app: injection and child forms questions

I have an existing 90k+ line Winforms application that I am trying to refactor, add unit testing to, add dependency injection to, and eventually get it over to an MVC architecture.

And so I'm trying to figure out how to use Unity Container with Winforms and get it going with at least injecting some dependencies that represent some Data Access Layer classes (mostly remote REST services).

Some bits of code regarding where I'm at:

Over in my Program.cs:

private static UnityContainer container;

public static void Main()
{
    container = new UnityContainer();
    container.RegisterType<IIncidentDataService, IncidentQuery>();
    container.RegisterType<IRuleService, RulesQuery>();

    Application.Run(container.Resolve<MainForm>());
}

Over in my MainForm.cs:

public partial class MainForm: Form
{
    private IIncidentDataServcie incidentDataService;
    private IRuleService ruleService;

    // constructor
    public MainForm(IIncidentDataService passedIncidentDataService, IRuleService passedRuleService)
    {
       this.InitializeComponent();
       incidentDataService = passedIncidentDataService;
       ruleService = passedRuleService;

     }

  <lots more code>
}

I realize I'm not doing this quite right yet. Certainly, I don't want to have to pass more and more parameters to the constructor on MainForm, as I have several other services yet to pass.

Now, one of the reason I have several other services to pass is that MainForm has controls on it that are used to summon child forms... and I'll need to pass service objects / dependencies over to those.

So, how SHOULD I be passing a container of multiple dependencies over to this Windows form?

I get the feeling I should be making one single object out of all of these service-classes... and passing that alone instead.

Upvotes: 1

Views: 1705

Answers (1)

Haukinger
Haukinger

Reputation: 10863

Application.Run(container.Resolve<MainForm>());

I realize I'm not doing this quite right yet.

To the contrary, this is as perfect as it gets.

Your keyword is factory - if MainForm needs to create an instance of SomeControl (that may have dependencies itself), inject an ISomeControlFactory (that has a SomeControl Create(); method) into MainForm.

Copying this answer:

For dependencies that are independent of the instance you're creating, inject them into the factory and store them until needed.

For dependencies that are independent of the context of creation but need to be recreated for each created instance, inject factories into the factory and store them.

For dependencies that are dependent on the context of creation, pass them into the Create method of the factory.

Upvotes: 3

Related Questions