Autofac WebApi 2 OWIN Not Working

2019-05-22 09:48发布

问题:

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?

回答1:

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.