Until now and still many implementation-prefer and rely on service collection classes for registering the dependency and using it through DI container.
Today in this post we will be using Generic HostBuilder to create DI Container and inject the required dependency within the Windows Forms app.
Creating Generic HostBuilder
Generic HostBuilder was introduced in .NET Core 2.1 and designed to be used for both Non-HTTP and HTTP workloads.
The HostBuilder class is available from the following namespace,
HostBuilder implements the IHostBuilder interface.
Please install the NuGet package from Nuget Package manager or PMC,
Please create Generic HosBuilder and register the dependencies that need to inject. These changes can be done in the Main() method.
Initialize the Host
Initialize the Host with all dependencies,
Or by using generic host builder CreateDefaultBuilder
Configure IoC Container- Dependency Injection in .NET Core WinForms
We shall be injecting Logger and BusinessLayer objects for more precise results. Please see below the complete code which we need to put in in Main() method application,
Here we are assuming Form1 as the master Form that will be an entry point for all other forms and their action.
However, you can add an additional layer separating actual UI components if needed.
All the services registered using HostBuilder are now available to use as per need. The lifetime management of those services will be taken care of by HostBuilder and we need not have disposed off them.
Form class for your references as below,
Let’s execute the application and try a button click action, where intentionally made it to the console view so that events can be captured.
Today we learned and attempted one more approach for leveraging the Dependency Injection (DI) in newly supported Windows forms applications in the .NET Core ecosystem. We learned that using Hostbuilder we can easily leverage DI in Desktop or Forms application and can create highly maintainable and extensible WinForms or desktop applications.