在 Web 应用程序中使用 structureMap 示例包

Using structureMap sample package in web application

我在我的应用程序中同时使用了 MVC 和 WebApi。为了实现 IoC,我使用结构图示例包(StructureMap.WebApi2)

在 MVC 控制器中一切正常,但是当我使用网络 api 时,例如 post 一些东西到服务器我得到这个错误:

[HttpException]: The controller for path '/api/Activity/AddActivity' was not found or does not implement IController.
   at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
   at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

这是 AddActivity 操作:

[HttpPost]
[ActionName("AddActivity")]
public HttpResponseMessage AddActivity(ActivityDTO activityDTO)
  {
      ActivityDTO data = activityDTO;
      HttpResponseMessage response = new HttpResponseMessage();

      data.UserID = User.Identity.GetUserId();

      int id = _activityServices.Add(data);

      if (id != -1)
      {
         response = this.Request.CreateResponse(HttpStatusCode.OK, id);
      }
      else
      {
         response=this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Activity doesn't save.");
      }

       return response;
  }

我查看了动作路径,是正确的

你能帮帮我吗?

谢谢

更新 1:

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        var container = IoCFactory.Container;

        GlobalConfiguration.Configuration.Services.Replace(
            typeof(IHttpControllerActivator), new IoCWebApiControllerFactory(container));

        config.MapHttpAttributeRoutes();

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

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

AjaxRequest:

$.post("/api/Activity/AddActivity", data)

你的问题不是依赖注入。在构造函数上放置一个断点并检查注入的依赖项是否不为空。如果这些不为空,则您的设置是正确的。

您遇到路由问题。当您使用 [ActionName("AddActivity")] 时,您应该有一个这样定义的路由:

routes.MapHttpRoute(
   name: "ActionApi",
   routeTemplate: "api/{controller}/{action}/{id}",
   defaults: new { id = RouteParameter.Optional } );

web-api 的默认 routeTemplate 没有 {action} 部分。另外你不应该在这里使用 ActionName,因为 it has a different purpose. Replace it with the Route attribute to use the attribute routing capabilities.