IServiceProvider in ASP.NET Core

后端 未结 7 1813
被撕碎了的回忆
被撕碎了的回忆 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<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

    0 讨论(0)
提交回复
热议问题