Using Dependency Injection with Startup.cs in ASP.NET Core

Full source code available here.

Did you know that .NET Core 2 can pass in an instance of any type you want to the Startup.cs constructor? Well you can! Here’s how.

Out of the box the Startup.cs comes like this -

1public class Startup
2{
3	public Startup(IConfiguration configuration)
4	{
5		Configuration = configuration;
6	}
7//snip..

The IConfiguration is passed in by dependency injection. In Program.cs you can add other types to the DI container, and then add that type to the constructor parameters of Startup.cs.

Here’s how it works. The [Microsoft.AspNetCore.Hosting.WebHostBuilder](https://github.com/aspnet/Hosting/blob/1f5379e38d201d329e28b50ecd080e999d274678/src/Microsoft.AspNetCore.Hosting/WebHostBuilder.cs#L96) has a ConfigureServices(...) method -

1public IWebHostBuilder ConfigureServices(Action<IServiceCollection> configureServices)
2{
3    if (configureServices == null)
4    {
5        throw new ArgumentNullException(nameof(configureServices));
6    }
7
8    return ConfigureServices((_, services) => configureServices(services));
9}

This lets you add services to the dependency injection container from the Program.cs.

WebHost.CreateDefaultBuilder(args) returns an IWebHostBuilder and that lets you use the ConfigureServices(...) method. Easy!

1public static IWebHost BuildWebHost(string[] args) =>
2    WebHost.CreateDefaultBuilder(args)
3        .ConfigureServices(serviceCollection =>
4            serviceCollection.AddScoped<ISomeService, SomeService>())
5        .UseStartup<Startup>()
6        .Build();

And in Startup.cs -

1public class Startup
2{
3    private ISomeService _someService;
4    public Startup(IConfiguration configuration, ISomeService someService)
5    {
6        _someService = someService;
7        Configuration = configuration;
8    }
9// snip..	

The instance of ISomeService is of course available for DI everywhere in the application.

1public class ValuesController : Controller
2{
3    private readonly ISomeService _someService;
4    public ValuesController(ISomeService someService)
5    {
6        _someService = someService;
7    }
8}

Full source code available here.

comments powered by Disqus

Related