我遇到了麻烦,让 Ninject 和 WebAPI.All 一起工作。我会更具体:
首先,我使用了 WebApi.All 包,看起来它对我来说很好用。
其次,我在 RegisterRoutes 下一行添加了 Global.asax:

routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));

所以最后的结果是:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

}

一切似乎都很好,但是当我尝试将用户重定向到特定操作时,类似:
return RedirectToAction("Index", "Home");
浏览器中的网址是 localhost:789/api/contacts?action=Index&controller=Home 这不好。我在 RegisterRoute 中交换了行,现在看起来:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

        }

现在重定向工作正常,但是当我尝试访问我的 API 操作时,我收到错误消息,告诉我 Ninject couldn't return controller "api" 这是绝对合乎逻辑的,我没有这样的 Controller 。
我确实搜索了一些如何使 Ninject 与 WebApi 一起工作的信息,但我发现的所有内容仅适用于 MVC4 或 .Net 4.5。由于技术问题,我无法将项目移至新平台,因此我需要为此版本找到有效的解决方案。
This answer 看起来像一个有效的解决方案,但是当我尝试启动项目时,我收到了编译器错误
CreateInstance = (serviceType, context, request) => kernel.Get(serviceType);

告诉我:System.Net.Http.HttpRequestMessage is defined in an assembly that is not referenced 和一些关于在程序集中添加引用的东西 System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
我不知道接下来要做什么,我找不到任何关于在 .NET 4 和 MVC3 上使用 webapi 进行 ninject 的有用信息。任何帮助,将不胜感激。

最佳答案

以下是我为您编译的几个步骤,可以帮助您入门:

  • 使用 Internet 模板
  • 创建一个新的 ASP.NET MVC 3 项目
  • 安装以下 2 个 NuGet:Microsoft.AspNet.WebApiNinject.MVC3
  • 定义一个接口(interface):
    public interface IRepository
    {
        string GetData();
    }
    
  • 和一个实现:
    public class InMemoryRepository : IRepository
    {
        public string GetData()
        {
            return "this is the data";
        }
    }
    
  • 添加一个 API Controller :
    public class ValuesController : ApiController
    {
        private readonly IRepository _repo;
        public ValuesController(IRepository repo)
        {
            _repo = repo;
        }
    
        public string Get()
        {
            return _repo.GetData();
        }
    }
    
  • 在您的 Application_Start 中注册一个 API 路由:
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        GlobalConfiguration.Configuration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    
        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
    
  • 使用 Ninject 添加自定义 Web API 依赖解析器:
    public class LocalNinjectDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver
    {
        private readonly IKernel _kernel;
    
        public LocalNinjectDependencyResolver(IKernel kernel)
        {
            _kernel = kernel;
        }
    
        public System.Web.Http.Dependencies.IDependencyScope BeginScope()
        {
            return this;
        }
    
        public object GetService(Type serviceType)
        {
            return _kernel.TryGet(serviceType);
        }
    
        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return _kernel.GetAll(serviceType);
            }
            catch (Exception)
            {
                return new List<object>();
            }
        }
    
        public void Dispose()
        {
        }
    }
    
  • Create 方法( ~/App_Start/NinjectWebCommon.cs )中注册自定义依赖解析器:
    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
    
        RegisterServices(kernel);
    
        GlobalConfiguration.Configuration.DependencyResolver = new LocalNinjectDependencyResolver(kernel);
        return kernel;
    }
    
  • RegisterServices 方法( ~/App_Start/NinjectWebCommon.cs )中配置内核:
    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IRepository>().To<InMemoryRepository>();
    }
    
  • 运行应用程序并导航到 /api/values
  • 10-06 13:39
    查看更多