How can I resolve from the IServiceProvider from inside my classes in ASP.NET Core?

You have to bring in Microsoft.Extensions.DependencyInjection namespace to gain access to the generic

GetService<T>();

extension method that should be used on

IServiceProvider 

Also note that you can directly inject services into controllers in ASP.NET 5. See below example.

public interface ISomeService
{
    string ServiceValue { get; set; }
}

public class ServiceImplementation : ISomeService
{
    public ServiceImplementation()
    {
        ServiceValue = "Injected from Startup";
    }

    public string ServiceValue { get; set; }
}

Startup.cs

public void ConfigureService(IServiceCollection services)
{
    ...
    services.AddSingleton<ISomeService, ServiceImplementation>();
}

HomeController

using Microsoft.Extensions.DependencyInjection;
...
public IServiceProvider Provider { get; set; }
public ISomeService InjectedService { get; set; }

public HomeController(IServiceProvider provider, ISomeService injectedService)
{
    Provider = provider;
    InjectedService = Provider.GetService<ISomeService>();
}

Either approach can be used to get access to the service. Additional service extensions for Startup.cs

AddInstance<IService>(new Service())

A single instance is given all the time. You are responsible for initial object creation.

AddSingleton<IService, Service>()

A single instance is created and it acts like a singleton.

AddTransient<IService, Service>()

A new instance is created every time it is injected.

AddScoped<IService, Service>()

A single instance is created inside of the current HTTP Request scope. It is equivalent to Singleton in the current scope context.

Updated 18 October 2018

See: aspnet GitHub – ServiceCollectionServiceExtensions.cs

Leave a Comment