Friday, October 1, 2021

How to use dependency injection in any .NET application

 If you work with ASP.NET applications, you know that it uses dependency injection mechanism. It is very convenient in many cases. But you may want to use the same mechanism in other types of applications: console, desktop, ... Here I'll show you how you can do it.

First of all, you need to install Microsoft.Extensions.DependencyInjection NuGet package. Then you must create an instance of ServiceCollection class.

var configurator = new ServiceCollection();

Now you can configure your dependencies.

configurator.AddScoped<Worker>();
configurator.AddScoped<Logger>();

When you finished configuration, you should create a service provider.

ServiceProvider services = configurator.BuildServiceProvider();

Then you can request instances of your services.

var worker = services.GetService<Worker>();

worker.Do();

That's it. Nice and easy. Happy coding!

No comments:

Post a Comment