Search code examples
c#.netwinformsdependency-injectionconstructor-injection

Can WinForms have dependencies injected without using a dependency injection framework?


I've read through many question on dependency injection in WinForms, with this being the most popular one. I was shocked to discover that every example I've seen on this website uses a library for this job, such as Microsoft.Extensions.DependencyInjection. This gives me my question: Can WinForms have dependencies injected without using a dependency injection framework?

For example, suppose that I have Form1 and Form2. Opening the application opens Form1. Form1 has a single button, which opens Form2. Both forms must have a SqlConnection injected. Can this be done without a dependency injection framework? For example, what forbids us from using plain-old constructor injection? I would expect Application.Run(new Form1(MySqlConnectionHere)) to work in Main()


Solution

  • Yes.

    See Mark Seemann's Pure DI concept.