dependency injection from scratch in .net core

Ivory Wolf
2 min readAug 15, 2020

--

Many of us are transitioning to .net core. For me, like many others, the change was a nesseccary of having to when having to migrate existing asp.net applications into the cloud. Often the first step is the Visual Studio wizard that produces a ready-to-go .net core web app. Great. We get scaffolding code furnished with IOC containers, Configuration, and even things like logging can be easily added — all things that I would have hand rolled or perhaps added. Many things are now available in the framework that would have previously required additional NuGet packages.

But create a simple console application and none of these features magically appear: we need to add them from scratch. Here I present a few articles showing how I have got these things up and running from scratch. Useful, I find, to get a better understanding of what is “given” to us by Visual Studio’s project templates and how they relate to the different flavours of applications we build.

In an asp.net core project we are familiar with the Startup.cs file that is generated for us. Here we the method find:

ConfigureServices(IServiceCollection services)

here we can add services to the container.

But where does the instance of IServiceCollection come from? and how to we retrieve the services added? Our controllers are auto-magically added and retrieved by the WebHost so it is not obvious at first.

Here’s how I do it in a simple .net core console application:

Dependencies:

Microsoft.Extensions.DependencyInjection — from NuGet

You can find the full solution on GitLab (link below). ApiClass is class made up for the example and does next-to-nothing but gives us something to register and retrieve.

There are a few hings happening:

  1. Create a service collection.
  2. Populate the service collection.
  3. Build and return a service provider.

Most examples fluently configure, build and return the IServiceProvider instance off the ServiceCollection() constructor. I’ve split it out here to remind myself that the ServiceCollection and ServiceProvider are two different things.

get the source code

next…

--

--