Dependency Inject a Service from Startup back to Program in .Net Core 3.1

Full source code available here.

Over the past couple of years I wrote a few posts about Dependency Injection in .Net Core 2.1, and this week I received comments from a reader telling me that some of the changes in .Net Core 3.1 mean that some of the approaches no longer work. There have been breaking changes.

I wanted to see what would still work so I tried a few things.

You can no longer DI from Program in Startup.

But you can add a transient service and/or a singleton service to the ServiceCollection and use it within Program, and the rest of the application. You can also add a scoped service to the ServiceCollection and use it within the Program, it’s a little different from using transient and singleton so I’ll cover it in the next post.

Here’s how to use transient and singletons inside Program. Create two services, creatively named ServiceOne and ServiceTwo and have them implement interfaces.

 1public class ServiceOne : IServiceOne
 3    public static int staticCounter;
 5    public ServiceOne()
 6    {
 7        staticCounter++;
 8    }
 9   //snip…
11public class ServiceTwo : IServiceTwo
13    public static int staticCounter;
15    public ServiceTwo()
16    {
17        staticCounter++;
18    }
19    //snip…

I added a static counter to make it easy to see how many times the constructor is called. For the transient one I expect it to increment every time the service is injected, for the singleton I expect it to remain at 1 for the lifetime of the application.

In Program.cs I split up CreateHostBuilder(args).Build call from the subsequent .Run().

1public static void Main(string[] args)
3    IHost host = CreateHostBuilder(args).Build();
4    DoSomethingWithTheTransientService(host.Services);
5    DoSomethingWithTheSingletonService(host.Services);
6    host.Run();

The CreateHostBuilder() method is not changed –

1public static IHostBuilder CreateHostBuilder(string[] args) =>
2    Host.CreateDefaultBuilder(args)
3    .ConfigureWebHostDefaults(webBuilder =>
4    {
5        webBuilder.UseStartup<Startup>();
6    });

And I have two methods that use the ServiceCollection to access the registered services –

 1private static void DoSomethingWithTheTransientService(IServiceProvider serviceProvider)
 3    Console.WriteLine("Calling the transient service");
 5    var serviceOne = serviceProvider.GetService<IServiceOne>();
 6    Console.WriteLine(serviceOne.StaticCounter());
 7    Console.WriteLine(serviceOne.GetHashCode());
10private static void DoSomethingWithTheSingletonService(IServiceProvider serviceProvider)
12    Console.WriteLine("Calling the singleton service");
14    var serviceTwo = serviceProvider.GetService<IServiceTwo>();
15    Console.WriteLine(serviceTwo.StaticCounter());
16    Console.WriteLine(serviceTwo.GetHashCode());

To make what’s happening more obvious I added the services to the constructor call of the WeatherForecastController() and added the counter and hash codes to the data returned by the action method.

1public class WeatherForecastController : ControllerBase
3    private IServiceOne _serviceOne;
4    private IServiceTwo _serviceTwo;
5    public WeatherForecastController(IServiceOne serviceOne, IServiceTwo serviceTwo)
6    {
7        _serviceOne = serviceOne;
8        _serviceTwo = serviceTwo;
9    }

For completeness, here is the ConfigureServices method in Startup.cs

1public void ConfigureServices(IServiceCollection services)
3    services.AddTransient<IServiceOne, ServiceOne>();
4    services.AddSingleton<IServiceTwo, ServiceTwo>();
5    services.AddControllers();

Put some breakpoints in Program Main(), DoSomethingWithTheTransientService(), DoSomethingWithTheSingletonService() and in the WeatherForecastController.Get().

Start the application and browse to http://localhost:5000/weatherforecast to see what happens.

I’m going to follow up on this post with a version that shows how to use scoped dependencies in Startup .NET 5.

Full source code available here.

comments powered by Disqus