c# - Autofac 结合 RegisterApiControllers 在 ApiController 上注入(inject)属性

标签 c# asp.net-web-api autofac autofac-configuration

我想将 autofac.json 文件中的 ModulesData 属性注入(inject)到我的 ApiController 中,名称为数据 Controller

我读了这个页面: http://docs.autofac.org/en/latest/configuration/xml.html但我的属性一直为 NULL,所以我一定是做错了什么。谁能帮帮我?

我的 Controller 已经有一个构造函数,其中正在注入(inject) ILog 的实例,因此这些属性是额外的。

这是我现在的 Autofac 配置:

var builder = new ContainerBuilder();
builder.RegisterApiControllers(typeof(Startup).Assembly); // to register all ApiControllers at once

// Use the Microsoft Configuration Extensions together with Autofac to create an Autofac Module
var autofacConfig = new ConfigurationBuilder();
autofacConfig.AddJsonFile("autofac.json");
var autofacModule = new  ConfigurationModule(autofacConfig.Build());
builder.RegisterModule(autofacModule);

var container = builder.Build();

var httpConfigurationConfig = new HttpConfiguration { DependencyResolver = new AutofacWebApiDependencyResolver(container) };

app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(httpConfigurationConfig );
app.UseWebApi(httpConfigurationConfig );

这是我的autofac.json:

{
  "components": [
    {
      "type": "Web.Controllers.DataController, Web",
      "injectProperties": true,
      "properties": {
        "Modules": {
          "Module1": "http://localhost:12345/",
          "Module2": "http://localhost:12346/"
        },
        "Data": {
          "Item1": "Declarations",
          "Item2": "Payments"
        }
      }
    }
  ]
}

我的 Controller 看起来像这样:

namespace Web.Controllers
{
    public class DataController : ApiController
    {
        private readonly ILog _log;
        public Dictionary<string, string> Modules { get; set; } // << I want these to be injected!
        public Dictionary<string, string> Data { get; set; }    // <<

        public DataController(ILog log) // gets injected
        {
            _log = log;
        }
    }
}

最佳答案

我没看到您将容器插入 WebApi 管道的什么位置?

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

另外,当你想要属性注入(inject)时,你需要使用方法PropertiesAutowired()

builder.RegisterApiControllers(typeof(Startup).Assembly).PropertiesAutowired();

关于c# - Autofac 结合 RegisterApiControllers 在 ApiController 上注入(inject)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278196/

相关文章:

c# - .Net Web API 路由和帮助页面

c# - 如何使用列表框将文本文件字符串发送到文本框?

c# - 如何从 litjson 中读取 bool 值

visual-studio - Visual Studio : Unit Testing a web project in the same solution

c# - Autofac 模块有自己的依赖项

c# - 使用 Autofac 解析通用接口(interface)

nservicebus - 通过 NServiceBus.Host.exe 启动端点时出现异常

c# - 为什么 "ref"关键字与 System.ServiceModel.Channels.Message 一起使用?

c# - 从两个列表中计算所有可能的项目对?

c# - 在使用 Json.Net 的 WebAPI 2 中,SQL Server 时间戳序列化但不反序列化