ASP.NET Core中的IServiceProvider [英] IServiceProvider in ASP.NET Core
问题描述
我开始学习ASP.NET 5(vNext)中的更改 并且找不到如何获取IServiceProvider,例如在模型"的方法中
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
{
public void DoSomething()
{
var dbContext = ServiceContainer.GetService<DataContext>(); //Where is ServiceContainer or something like that ?
}
}
我知道,我们在启动时配置服务,但是所有服务集合还是IServiceProvider保留在哪里?
I know, we configuring services at startup, but where all service collection staying or IServiceProvider?
推荐答案
您必须引入Microsoft.Extensions.DependencyInjection
命名空间才能访问通用
You have to bring in Microsoft.Extensions.DependencyInjection
namespace to gain access to the generic
GetService<T>();
应在
IServiceProvider
还请注意,您可以将服务直接注入ASP.NET 5中的控制器中.请参见下面的示例.
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
Startup.cs
public void ConfigureService(IServiceCollection services)
{
...
services.AddSingleton<ISomeService, ServiceImplementation>();
}
HomeController
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>();
}
这两种方法均可用于访问服务. Startup.cs的其他服务扩展
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>()
在当前HTTP请求范围内创建一个实例.在当前作用域上下文中,它等效于Singleton.
A single instance is created inside of the current HTTP Request scope. It is equivalent to Singleton in the current scope context.
更新于2018年10月18日
请参阅: aspnet GitHub-ServiceCollectionServiceExtensions.cs
这篇关于ASP.NET Core中的IServiceProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!