Resolving instances with ASP.NET Core DI

asp.net core get service provider
asp.net core dependency injection factory
asp.net core get service provider in controller
.net core dependency injection with parameters
when to use scoped vs transient
.net core dependency injection runtime parameters
.net core dependency injection static class
conditional dependency injection asp.net core

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 ISomeService without performing injection? For example, I want to do this:

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

There are no such methods in IServiceCollection.

The IServiceCollection interface is used for building a dependency injection container. After it's fully built, it gets composed to an IServiceProvider instance which you can use to resolve services. You can inject an IServiceProvider into any class. The IApplicationBuilder and HttpContext classes can provide the service provider as well, via their ApplicationServices or RequestServices properties respectively.

IServiceProvider defines a GetService(Type type) method to resolve a service:

var service = (IFooService)serviceProvider.GetService(typeof(IFooService));

There are also several convenience extension methods available, such as serviceProvider.GetService<IFooService>() (add a using for Microsoft.Extensions.DependencyInjection).

Resolving services inside the startup class
Injecting dependencies

The runtime's hosting service provider can inject certain services into the constructor of the Startup class, such as IConfiguration, IWebHostEnvironment (IHostingEnvironment in pre-3.0 versions), ILoggerFactory and IServiceProvider. Note that the latter is an instance built by the hosting layer and contains only the essential services for starting up an application.

The ConfigureServices() method does not allow injecting services, it only accepts an IServiceCollection argument. This makes sense because ConfigureServices() is where you register the services required by your application. However you can use services injected in the startup's constructor here, for example:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // Use Configuration here
}

Any services registered in ConfigureServices() can then be injected into the Configure() method; you can add an arbitrary number of services after the IApplicationBuilder parameter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IFooService>();
}

public void Configure(IApplicationBuilder app, IFooService fooService)
{
    fooService.Bar();
}
Manually resolving dependencies

If you need to manually resolve services, you should preferably use the ApplicationServices provided by IApplicationBuilder in the Configure() method:

public void Configure(IApplicationBuilder app)
{
    var serviceProvider = app.ApplicationServices;
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();
}

It is possible to pass and directly use an IServiceProvider in the constructor of your Startup class, but as above this will contain a limited subset of services, and thus has limited utility:

public Startup(IServiceProvider serviceProvider)
{
    var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>();
}

If you must resolve services in the ConfigureServices() method, a different approach is required. You can build an intermediate IServiceProvider from the IServiceCollection instance which contains the services which have been registered up to that point:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IFooService, FooService>();

    // Build the intermediate service provider
    var sp = services.BuildServiceProvider();

    // This will succeed.
    var fooService = sp.GetService<IFooService>();
    // This will fail (return null), as IBarService hasn't been registered yet.
    var barService = sp.GetService<IBarService>();
}

Please note: Generally you should avoid resolving services inside the ConfigureServices() method, as this is actually the place where you're configuring the application services. Sometimes you just need access to an IOptions<MyOptions> instance. You can accomplish this by binding the values from the IConfiguration instance to an instance of MyOptions (which is essentially what the options framework does):

public void ConfigureServices(IServiceCollection services)
{
    var myOptions = new MyOptions();
    Configuration.GetSection("SomeSection").Bind(myOptions);
}

Manually resolving services (aka Service Locator) is generally considered an anti-pattern. While it has its use-cases (for frameworks and/or infrastructure layers), you should avoid it as much as possible.

Resolving ASP.NET Core Startup class from the DI container , What most users of ASP.NET Core do not realize, is that at runtime, the Startup instance is actually being resolved from the DI container. 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>(); }

Manually resolving instances involves using the IServiceProvider interface:

Resolving Dependency in Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IMyService, MyService>();

    var serviceProvider = services.BuildServiceProvider();
    var service = serviceProvider.GetService<IMyService>();
}
Resolving Dependencies in Startup.Configure
public void Configure(
    IApplicationBuilder application,
    IServiceProvider serviceProvider)
{
    // By type.
    var service1 = (MyService)serviceProvider.GetService(typeof(MyService));

    // Using extension method.
    var service2 = serviceProvider.GetService<MyService>();

    // ...
}
Resolving Dependencies in Startup.Configure in ASP.NET Core 3
public void Configure(
    IApplicationBuilder application,
    IWebHostEnvironment webHostEnvironment)
{
    app.ApplicationServices.GetService<MyService>();
}
Using Runtime Injected Services

Some types can be injected as method parameters:

public class Startup
{
    public Startup(
        IHostingEnvironment hostingEnvironment,
        ILoggerFactory loggerFactory)
    {
    }

    public void ConfigureServices(
        IServiceCollection services)
    {
    }

    public void Configure(
        IApplicationBuilder application,
        IHostingEnvironment hostingEnvironment,
        IServiceProvider serviceProvider,
        ILoggerFactory loggerfactory,
        IApplicationLifetime applicationLifetime)
    {
    }
}
Resolving Dependencies in Controller Actions
[HttpGet("/some-action")]
public string SomeAction([FromServices] IMyService myService) => "Hello";

ASP.NET Core Dependency Injection Best Practices, Tips & Tricks, ASP.NET Core's standard dependency injection container does not support property injection. But you DI container keeps track of all resolved services. Because the transient service becomes a singleton instance when a  to be able to resolve instances with ASP.NET Core DI in static classes, you need a full “service provider” that contains the services you already have added from your startup.cs class. Isn’t enough create a new instance of IServiceProvider and use it.

If you generate an application with a template you are going to have something like this on the Startup class:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();
}

You can then add dependencies there, for example:

services.AddTransient<ITestService, TestService>();

If you want to access ITestService on your controller you can add IServiceProvider on the constructor and it will be injected:

public HomeController(IServiceProvider serviceProvider)

Then you can resolve the service you added:

var service = serviceProvider.GetService<ITestService>();

Note that to use the generic version you have to include the namespace with the extensions:

using Microsoft.Extensions.DependencyInjection;

ITestService.cs

public interface ITestService
{
    int GenerateRandom();
}

TestService.cs

public class TestService : ITestService
{
    public int GenerateRandom()
    {
        return 4;
    }
}

Startup.cs (ConfigureServices)

public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddMvc();

    services.AddTransient<ITestService, TestService>();
}

HomeController.cs

using Microsoft.Extensions.DependencyInjection;

namespace Core.Controllers
{
    public class HomeController : Controller
    {
        public HomeController(IServiceProvider serviceProvider)
        {
            var service = serviceProvider.GetService<ITestService>();
            int rnd = service.GenerateRandom();
        }

ASP.NET Core: Inject all instances of a service interface, ASP.NET Core: Inject all instances of a service interface it comes to Dependency Injection (DI), the functionality provided by ASP.net core is simple, but powerful. I was stunned by how easy it is to resolve multiple registered  Resolving ASP.NET Core Startup class from the DI container. In ASP.NET Core, the most common setup is characterized by having a standalone Startup class, responsible for bootstrapping the services needed by your application, as well as setting up the application pipeline. What most users of ASP.NET Core do not realize, is that at runtime, the Startup instance is actually being resolved from the DI container.

If you just need to resolve one dependency for the purpose of passing it to the constructor of another dependency you are registering, you can do this.

Let's say you had a service that took in a string and an ISomeService.

public class AnotherService : IAnotherService
{
    public AnotherService(ISomeService someService, string serviceUrl)
    {
        ...
    }
}

When you go to register this inside Startup.cs, you'll need to do this:

services.AddScoped<IAnotherService>(ctx => 
      new AnotherService(ctx.GetService<ISomeService>(), "https://someservice.com/")
);

Dependency injection in ASP.NET Core, Resolving instances with ASP.NET Core DI in static classes when is no possible use Dependency Injection, but you need to use some injected  There are 3 options for this with the built-in DI container in ASP.NET Core: Singleton; Scoped; Transient; Singleton means only a single instance will ever be created. That instance is shared between all components that require it. The same instance is thus used always. Scoped means an instance is created once per scope. A scope is created on

You can inject dependencies in attributes like AuthorizeAttribute in this way

var someservice = (ISomeService)context.HttpContext.RequestServices.GetService(typeof(ISomeService));

Resolving instances with ASP.NET Core DI in static classes , In ASP.NET Core 3.0, endpoint routing is the suggested approach for method calls ConfigureServices() on the IWebHostBuilder instance, and configures some settings. As these services are configured in the DI container before Startup is InvalidOperationException: Unable to resolve service for type  ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core .

Avoiding Startup service injection in ASP.NET Core 3: Upgrading to , Net Core, the only way to get DI in your applications was through the use of a framework However, DI is treated as a first-class citizen in ASP. When a request gets routed to your controller, it will be resolved from the You would just return an instance of the container in your ConfigureServices method. In ASP.NET Core 2 Web Api, I want to use dependency injection to inject httpClientA instance of HttpClient to ControllerA, and an instance httpClientB of the HttpClient to ControllerB. The DI registration code would look something like:

.Net Core Dependency Injection, If you go to the official docs for ASP.NET Core you'll find that Dependency Injection is under the “fundamentals” area. At runtime we rely on the DI system to create new instances of these objects for us. Resolving refers to the process of figuring out what dependencies are required for a particular service  So, I think the default DI in ASP.NET Core is missing two things: The ability to register instances using a key; The ability to inject static data into constructors during registration

NET Core Dependency Injection: Everything You , ASP.NET Core MVC controllers should request their dependencies explicitly To specify that requests for IDateTime should be resolved using an instance of  c# - ASP.NET Core resolving DbContext in Service - Stack Overflow. I have issue with resolving DbContext in my UserManager class. Here is UserManager class:public class UserManager : IUserManager{ private readonly MyContext _context; public UserManager(. Stack Overflow. Products. Customers.

Comments
  • possible duplicate of How to Resolve Instance Inside ConfigureServices in ASP.NET 5
  • Do you want to resolve them in the ConfigureServices() method (with IServiceCollection) or just anywhere in the application?
  • @HenkMollema: Anywhere within Startup actually.
  • @HenkMollema but what if i can't have anything injected, I mean I can't have IServiceCollection injected, some class that is being created manually(out of middle ware scope), a scheduler in my case, which periodically needs some services to generate and send an email.
  • warning if you need to resolve services in ConfigureServices and that service is a singleton it will be a different singleton to the one your Controllers use! I assume this is because it uses a different IServiceProvider - to avoid this do NOT resolve via BuildServiceProvider and instead move your lookup of the singleton from ConfigureServices to Configure(..other params, IServiceProvider serviceProvider) in Startup.cs
  • @wal good point. Because it's a different IServiceProvider instance it will create a new singleton instance. You could avoid this by returning the service provider instance from the ConfigureServices method so that will be the container your application uses as well.
  • Invoking collection.BuildServiceProvider(); was what I needed, thanks!
  • @HenkMollema how do you make it work with only one service provider instance? Typically, you would 1) Register some of your dependencies 2) build an interim service provider instance 3) Use that service provider to resolve something you need to register some other dependencies. Afterwards, you can't return the interim instance, since it's missing some of your dependencies (registered in 3). Am I missing something?
  • @AfsharMohebbi the GetService which is generic is an extension method in Microsoft.Extensions.DependencyInjection namespace.
  • About Extension Methods: An extension method is a static method that adds funcionality to a class, you could declare public static TheReturnType TheMethodName(this TheTypeYouExtend theTypeYouExtend { // BODY} and then you could use it like: TheTypeYouExtend.TheMethodName(); That has become a very common aproach with .NET Core, so that developers can extend base functionality... good examples here: docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
  • The [FromServices] annotation is neat, thanks!