gpt4 book ai didi

configuration - 在 MVC 6 中访问依赖注入(inject)服务

转载 作者:行者123 更新时间:2023-12-04 06:25:58 24 4
gpt4 key购买 nike

我在 vs2015 rc 中使用 mvc6。看完Using IConfiguration globally in mvc6 ,我的代码现在看起来像这样:

启动.cs:

public void ConfigureServices(IServiceCollection services)
{
...
IConfiguration configuration = new Configuration().AddJsonFile("config.json");
services.Configure<Settings>(configuration);
}

我的 Controller :

private Settings options;
public MyController(IOptions<Settings> config)
{
options = config.Options;
}

这对 Controller 非常有用。

但是我如何从代码中的其他地方访问我的 Settings 对象,例如从我的 Formatters(实现 IInputFormatter,因此具有固定签名)或任何其他随机类?

最佳答案

一般来说,只要您有权访问 HttpContext,就可以使用名为 RequestServices 的属性来访问 DI 中的服务。例如,要从 ObjectResult 中访问 ILogger 服务.

public override async Task ExecuteResultAsync(ActionContext context)
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ObjectResult>>();

上面的用法与你在上面的 Controller 示例中提到的有点不同,因为 MVC 中的 Controller 是 type activated...也就是说,构建 Controller 的责任是通过 DI 管理的,它将查看构造函数的参数并从 DI 中的注册服务填充它们...这也称为 构造函数注入(inject)...

要了解 DI 类型激活的一般工作原理(DI 独立于 MVC,甚至可以在控制台应用程序中使用),请查看以下代码片段(摘自 http://docs.asp.net/en/latest/security/data-protection/using-data-protection.html)

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

在上面的示例中,类型 MyClass 被类型激活。

关于您关于 InputFormatter 的具体示例,它们不是类型激活的,因此您不能对其使用构造函数注入(inject),但您可以访问 HttpContext,因此您可以按照本文前面提到的那样进行操作。

另请参阅这篇文章:http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx

关于configuration - 在 MVC 6 中访问依赖注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com