Autofac inject properties on ApiController in combination with RegisterApiControllers

405 Views Asked by At

I want to inject Modules and Data properties from an autofac.json file into my ApiController with name DataController

I read this page: http://docs.autofac.org/en/latest/configuration/xml.html but my properties keep being NULL, so I must be doing wrong something. Who can help me?

My Controller already has an contructor where an instance of ILog is being injected, so these properties are extra.

This is the Autofac configuration I have now:

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

This is my 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"
        }
      }
    }
  ]
}

My Controller looks like this:

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;
        }
    }
}
2

There are 2 best solutions below

1
On

I don't see where you plug in the container in the WebApi pipeline ?

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

Additionally, when you want property injection, you need to use the method PropertiesAutowired()

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

The code you provide seems to be fine - I copied it and it works fine.

You must remember that properties are injected after the component is created, so in you controller constructor these properties are null, but when you hit the controller method, they are filled with proper data you provided in your json configuration file.