Organize your DI registrations into modules when using built in DI in .NET Core

I love Microsoft.Extensions.DependencyInjection a.k.a Built in DI in .NET core. Although it lacks some of the advance configurations supported by other DI frameworks like Autofac, the reason it wins me over every time is the simplicity and its super lightweight.

One of the things it lacks in basic usage scenarios is that the ability to organize your registrations in the assembly level and not exposing everything in public methods. Or maybe I’m spoilt by Ninject and Autofac.

Advantages of using DI modules.

  1. A cleaner way to manage all DI bindings in one place.
  2. Ability to make bindings modular.
  3. Multiple callers can register services of an assembly without doing all the registrations multiple times.
  4. You can make interfaces public and implementations internal (abstraction).

There are two super easy ways to achieve that in .NET Core built in DI

  1. Use Katalogo nuget package
  2. Extend for your needs

If you prefer Katalogo, then by all means stop reading and implement it. But I personally prefer the 2nd option since it takes only 5 mins of implementation and pretty much the same amount of code as Katalogo implementation.

Let’s create a static class where all your registrations for a class library or application will live. This is your module class. I will call this “BindingModule.cs”.

public static class BindingModule
	public static void AddBindings(this IServiceCollection services)
		services.AddSingleton<IHelloService, HelloService>();

BindingModule.cs Here you get to define all your bindings. And then we call all our bindings in the main entrypoint.

private static IHostBuilder CreateHostBuilder(string[] args)
	var hostBuilder = Host.CreateDefaultBuilder(args)
		.ConfigureAppConfiguration((context, builder) =>
		.ConfigureServices((context, services) =>
			//add your service registrations

	return hostBuilder;

That’s it.

Let me know if I have missed anything or if anything needs more clarification in the comments below.

comments powered by Disqus