davenewza davenewza - 1 year ago 256
C# Question

Resolving instances with ASP.NET Core DI

How do I manually resolve a type using the ASP.NET Core MVC built-in dependency injection framework?

Setting up the container is easy enough:

public void ConfigureServices(IServiceCollection services)
// ...

services.AddTransient<ISomeService, SomeConcreteService>();

But how can I resolve
without performing injection? For example, I want to do this:

ISomeService service = services.Resolve<ISomeService>();

There are no such methods in

Answer Source

There are several options in the Startup class.

Injecting dependencies
The runtime can inject runtime services in the constructor of the Startup class, such as IHostingEnvironment and IServiceProvider.

Services can also be injected in the Configure() method. You can add an arbitrary amount of parameters after the IApplicationBuilder parameter. You can also inject your own services which are registered in the ConfigureServices() method here. The ConfigureServices() method however does not allow injecting services, it only accepts an IServiceCollection argument.

Manually resolving dependencies
If you want to manually resolve services, you can let the runtime inject a IServiceProvider instance in the constructor and the Configure() method:

public Startup(IServiceProvider serviceProvider)
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();


public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();

However, if you need to resolve services in the ConfigureServices() method, you need a different approach. You can build a intermediate IServiceProvider from an IServiceCollection instance which contains the services which are registered until then:

public void ConfigureService(IServiceCollection services)
    services.AddSingleton<ISomeService, SomeService>();

    // Build the intermediate service provider
    var sp = services.BuildServiceProvider();
    var service = sp.GetService<ISomeService>();

You need the Microsoft.Extensions.DependencyInjection package for this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download