【问题标题】:Accessing dependency injected services in MVC 6在 MVC 6 中访问依赖注入服务
【发布时间】:2015-08-04 03:54:47
【问题描述】:

我将 mvc6 与 vs2015 rc 一起使用。看完Using IConfiguration globally in mvc6,我的代码现在是这样的:

startup.cs:

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

我的控制器:

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

这对控制器非常有用。

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

【问题讨论】:

    标签: configuration asp.net-core asp.net-core-mvc


    【解决方案1】:

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

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

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

    要了解 DI 类型激活的一般工作原理(DI 独立于 MVC,甚至可以在控制台应用程序中使用),请查看以下 sn-p 代码(取自 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 的具体示例,它们是 not 类型激活的,因此您不能对其使用构造函数注入,但您可以访问 HttpContext,因此您可以这样做如本文前面所述。

    也可以看看这篇文章:http://blogs.msdn.com/b/webdev/archive/2014/06/17/dependency-injection-in-asp-net-vnext.aspx

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 1970-01-01
      • 2018-12-03
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多