无法让 Autofac 与 Web 一起工作 API 2

Cannot get Autofac to work with Web API 2

我正在努力让 Autofac 与 WebApi2 控制器一起工作

我总是得到没有无参数构造函数的错误

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "An error occurred when trying to create a controller of type 'GatewayController'. Make sure that the controller has a parameterless public constructor.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Type 'Gv8ApiGateway.Controllers.GatewayController' does not have a default constructor".....
    }
}

我在这个网上看了很多帖子,我看不出我错过了什么

当我在构建容器后查看它时,我可以看到它确实包含我的控制器

我正在使用 TopShelf

    HostFactory.Run(x => //1
    {
        x.UseAutofacContainer(container);

        x.Service<IMyService>(s => //2
        {
            s.ConstructUsingAutofacContainer();
            s.WhenStarted(tc => tc.Start());
            s.WhenStopped(tc => tc.Stop());
        });
        x.SetStartTimeout(TimeSpan.FromMinutes(4));
        x.StartAutomatically();
        x.RunAsLocalSystem();
        x.EnableServiceRecovery(r => { r.RestartService(0); });
        x.SetDescription($"DESCRIPTION");
        x.SetDisplayName($"DISPLAY NAME");
        x.SetServiceName($"NAME");
    });

在我的汇编模块中,我已验证正在调用的行

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

在由 TopShelf 启动的 class 中,我有 -

var resolver = new AutofacWebApiDependencyResolver(_container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
_webApi = WebApp.Start<Startup>("http://localhost:8084");

我的启动 class 是 -

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Configure Web API for self-host. 
        var config = new HttpConfiguration();

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional}
        );

        app.UseWebApi(config);


    }
}

我认为关键是我设置依赖解析器的地方,但我调用它的地方似乎没有任何区别,即在我开始 API

之前或之后

我的控制器是:

public class GatewayController : ApiController
{
    private readonly IMyService_myService;

    public GatewayController(IMyService myService)
    {
        Argument.IsNotNull(() => myService);

        _myService = myService;
    }


}

谁能看出我做错了什么?

您必须像下面这样在容器中注册您的服务和接口。

container.Register<IMyService, MyService>();

在TopSelf配置设置之前,添加上面的代码。它会起作用。

您的 Web API 启动 class 显示您正在使用 OWIN 管道。我们看到了这一点,因为您正在从头开始创建 HttpConfiguration

app.UseWebApi(config);

If you check out the documentation on Web API OWIN integration 你可以看到一个例子,说明它是如何变化的。 关键是你要设置config.DependencyResolver,而不是GlobalConfiguration.DependencyResolver

如文档中所述:

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.

请注意,有几个额外的步骤可以确保 OWIN 管道与 Autofac 一起正常工作。 There are docs on setting up the base OWIN pipeline and there's additional Autofac Web API specific middleware that needs to be added

我在您的 Web API 启动中没有看到任何 Autofac 中间件,因此这也可能会导致问题。我建议您回去查看其中的一些文档。