2

我想将文件中的属性ModulesData属性注入autofac.json到我ApiController的名字中DataController

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

Controller已经有一个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;
        }
    }
}
4

2 回答 2

0

您提供的代码似乎很好 - 我复制了它,它工作正常。

您必须记住,属性是在创建组件注入的,因此在您的控制器构造函数中,这些属性是null,但是当您点击控制器方法时,它们会填充您在 json 配置文件中提供的正确数据。

于 2017-07-27T08:03:36.140 回答
0

我没有看到您在 WebApi 管道中插入容器的位置?

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

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

builder.RegisterApiControllers(typeof(Startup).Assembly).PropertiesAutowired();
于 2017-07-24T10:41:09.753 回答