2
votes

Having an issue with Autofac and WebApi2 using OWIN. Basically the Constructor isn't getting Injected.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "Default Route",
            routeTemplate: "{controller}.{ext}"
        );

        config.Routes.MapHttpRoute(
            name: "Default Route with Id",
            routeTemplate: "{controller}/{id}.{ext}",
            defaults: new { id = RouteParameter.Optional }
        );

        var builder = new ContainerBuilder();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.Register(c => new Logger()).As<ILogger>().InstancePerRequest();

        var container = builder.Build();
        var resolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;

        app.UseAutofacWebApi(GlobalConfiguration.Configuration);
        app.UseWebApi(config);
    }
}

public class UsersController : ApiController
{
    private readonly ILogger _logger;

    public UsersController(ILogger logger)
    {
         _logger = logger;
    }
}

I'm using the Autofac.Integration.Owin nuget alpha package. What am I missing?

2

2 Answers

11
votes

Try using the config configuration object all the way through. In the middle you switch to GlobalConfiguration. In OWIN + Web API you won't use the static configuration object, just the instance you create while configuring the OWIN app.

0
votes

It is not recommended to use GlobalConfiguration at all with OWIN integration, rather use only the configuration you create.

From Autofac Documentation - A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.