Discover how you can get APIs and microservices to work at true enterprise scale.

The Dependency Injection (DI) Container used in ASP.NET Core is not limited to ASP.NET Core. You are able to use it in any kind of .NET project. This post shows how to use it in an .NET Core Console application.

Create a Console Application using the dotnet CLI or Visual Studio 2017. The DI Container is not available by default, but the IServiceProvider is. If you want to use an Custom or third party DI Container, you should provide an implementation if an IServiceProvider, as an encapsulation of a DI Container.

In this post, I want to use the DI Container used in the ASP.NET Core projects. This needs an additional NuGet package, Microsoft.Extensions.DependencyInjection (currently, it is version 1.1.0).

Since this library is a .NET Standard Library, it should also work in a .NET 4.6 application. You just need to add a reference to Microsoft.Extensions.DependencyInjection.

After adding that package, we can start to use it. I created two simple classes that are dependent of each other to show the how it works in a simple way:

This ServiceCollection comes from the added NuGet package. Your favorite DI container possibly uses another way to register the services. You can now share the ServiceCollection to additional components who want to share some more services in the same way ASP.NET Core does with the AddSomething (i.e., AddMvc())) extension methods.

Now, we need to create the ServiceContainer out of that collection:

var provider = services.BuildServiceProvider();

We can also share the ServiceProvider in our application to retrieve the services, but the proper way is to use it only on a single entry point:

using (var service1 = provider.GetService<Service1>()) {
// so something with the class
}