2

I have the following WebAPI Controller (I have removed most of the code for brevity)

public class ConnectionController : ApiController
{
    /// <summary>
    /// Gets or sets the connection manager.
    /// </summary>
    /// <value>
    /// The connection manager.
    /// </value>
    public IConnectionManagerService ConnectionManager
    {
        get;
        set;

    }

}

I am trying to insert the IConnectionManagerService through AutoFac and this is the code I have so far

// Create the container builder.
var builder = new ContainerBuilder();

// Register the Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

// Register other dependencies.
builder.Register(c => new ConnectionManagerService()).As<IConnectionManagerService>().InstancePerRequest();                      

// Build the container.
var container = builder.Build();

// Create the depenedency resolver.
var resolver = new AutofacWebApiDependencyResolver(container);

// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = resolver;

Now inside the controller when I try to Use ConnectionManager I get null. I thought Autofac will automatically include the dependency? I dont want to include this dependency through a constructor parameter in the controller.

user3547774
  • 1,621
  • 3
  • 20
  • 46
  • Is there any other concrete reason to not you constructor injection beside that you don't want to do that? – nemesv Jul 23 '14 at 05:25
  • Not really, I just want to stick to the standard that comes out of the box as much as possible rather than making modifications to support DI. – user3547774 Jul 23 '14 at 05:32
  • 1
    It is considered best practice to use constructor injection. Don't be mislead to the code the Visual Studio generates by default. The default VS templates often don't communicate best practices. – Steven Jul 23 '14 at 05:37
  • To use constructor injection, do I need to make any chances to the Controller, I actually did try constructor injection, but it does not even instantiate the constructor, I am sure I am missing something here. – user3547774 Jul 23 '14 at 05:43

1 Answers1

0

To achieve properties injection in Autofac you should just use PropertiesAutowired extension method. In your autofac configuration after line:

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

insert line:

builder.RegisterType<ConnectionController>().PropertiesAutowired();

Then if something is registerd in your container builder as IConnectionManagerService it will be assigned to ConnectionManager property.

mr100
  • 4,340
  • 2
  • 26
  • 38