IServiceProvider in ASP.NET Core

后端 未结 7 1815
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 08:02

I starting to learn changes in ASP.NET 5(vNext) and cannot find how to get IServiceProvider, for example in \"Model\"\'s method

public class Entity 
{
     publ         


        
7条回答
  •  醉话见心
    2021-02-02 08:40

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

    GetService();
    

    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();
    }
    

    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();
    }
    

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

    AddInstance(new Service())
    

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

    AddSingleton()
    

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

    AddTransient()
    

    A new instance is created every time it is injected.

    AddScoped()
    

    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

提交回复
热议问题