How to List All Services Available to an ASP.NET Core App

How to List All Services Available to an ASP.NET Core App

In a recent article, I showed how to configure logging for your Startup class in ASP.NET Core. With this configured, it’s easy to log all of the services that have been configured in ASP.NET Core services container. This can be very useful when diagnosing issues with ASP.NET Core’s support for dependency injection. Grab the code from the other post to get access to the logger in your ConfigureServices method, then add this:

This will produce output like this, when you run the application:

Startup Services

Of course, if you’d rather see the services in your browser than just in your logging, you can create some simple middleware that will display them. First, in your Startup class, create a field _services of type IServiceCollection. Then, at the end of ConfigureServices, assign the services parameter to the _services field.

Then, in configure, set up the middleware to map a particular URL to list out the contents of _services. I recommend you only do this for the Development environment. Below there are two options – use the app.Map call if you just want to add this functionality to an existing app. Otherwise use app.Run (which will respond to all request paths with the list of services).

You’ll probably want to add some CSS so this looks decent, but here’s the basic output:

startup-services-middleware

The code is available on GitHub here.

Now you have two easy ways to quickly see what’s in your services container in your ASP.NET Core app, so that you can better understand how ASP.NET Core works under the covers and manage your app’s dependencies. The dependency injection support in ASP.NET Core is much nicer than in previous versions of ASP.NET, and can really help you to produce more loosely-coupled, testable, more maintainable apps. Your classes will be better able to follow important principles like SOLID and the Explicit Dependencies Principle. Let me know what you think in the comments or on twitter, where I’m @ardalis.

  • I would be very economical with the number of awaits. On that loop, it would be better to have just one await WriteAsync. You really don’t need more.

    Better yet, use ConfigureAwait(false).

    • ardalis

      Good catch; I’ll update.

  • MotoWilliams

    smh StructureMap.WhatDoIHave

    • ardalis

      I’ve never had much success with formatting the output from that method…