Configuration 在MVC6中访问依赖注入服务
我将mvc6与vs2015 rc一起使用。阅读后,我的代码如下所示: startup.cs:Configuration 在MVC6中访问依赖注入服务,configuration,asp.net-core,asp.net-core-mvc,Configuration,Asp.net Core,Asp.net Core Mvc,我将mvc6与vs2015 rc一起使用。阅读后,我的代码如下所示: startup.cs: public void ConfigureServices(IServiceCollection services) { ... IConfiguration configuration = new Configuration().AddJsonFile("config.json"); services.Configure<Settings>(configuratio
public void ConfigureServices(IServiceCollection services)
{
...
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
services.Configure<Settings>(configuration);
}
public void配置服务(IServiceCollection服务)
{
...
IConfiguration configuration=new configuration().AddJsonFile(“config.json”);
服务。配置(配置);
}
我的控制器:
private Settings options;
public MyController(IOptions<Settings> config)
{
options = config.Options;
}
私人设置选项;
公共MyController(IOptions配置)
{
options=config.options;
}
这对控制器非常有效
但是我如何从代码中的其他地方访问我的设置对象,例如从我的格式化程序(实现IIInputFormatter,因此使用固定签名)或任何其他随机类中访问设置对象?通常情况下,您可以访问
HttpContext
,您可以使用名为RequestServices
的属性来访问DI中的服务。例如,从内部访问ILogger
服务
在上面的示例中,类型MyClass
被激活
关于InputFormatter
的具体示例,它们不是类型激活的,因此您不能使用构造函数注入,但您可以访问HttpContext
,因此您可以像本文前面提到的那样进行操作
另请看这篇文章:
public override async Task ExecuteResultAsync(ActionContext context)
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ObjectResult>>();
using System;
using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.DependencyInjection;
public class Program
{
public static void Main(string[] args)
{
// add data protection services
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
// create an instance of MyClass using the service provider
var instance = ActivatorUtilities.CreateInstance<MyClass>(services);
instance.RunSample();
}
public class MyClass
{
IDataProtector _protector;
// the 'provider' parameter is provided by DI
public MyClass(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector("Contoso.MyClass.v1");
}
public void RunSample()
{
Console.Write("Enter input: ");
string input = Console.ReadLine();
// protect the payload
string protectedPayload = _protector.Protect(input);
Console.WriteLine($"Protect returned: {protectedPayload}");
// unprotect the payload
string unprotectedPayload = _protector.Unprotect(protectedPayload);
Console.WriteLine($"Unprotect returned: {unprotectedPayload}");
}
}
}