使用Ninject的Web API

时间:2012-10-21 09:17:53

标签: c# asp.net-mvc-3 .net-4.0 ninject

我遇到麻烦,制作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");

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"绝对合乎逻辑,我没有这样的控制器。

我确实搜索了一些如何使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上找不到关于ninject和webapi的任何有用信息。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:11)

以下是我为您编写的一些步骤,可以帮助您入门:

  1. 使用Internet模板
  2. 创建新的ASP.NET MVC 3项目
  3. 安装以下2个NuGets:Microsoft.AspNet.WebApiNinject.MVC3
  4. 定义界面:

    public interface IRepository
    {
        string GetData();
    }
    
  5. 并实施:

    public class InMemoryRepository : IRepository
    {
        public string GetData()
        {
            return "this is the data";
        }
    }
    
  6. 添加API控制器:

    public class ValuesController : ApiController
    {
        private readonly IRepository _repo;
        public ValuesController(IRepository repo)
        {
            _repo = repo;
        }
    
        public string Get()
        {
            return _repo.GetData();
        }
    }
    
  7. 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 }
        );
    }
    
  8. 使用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()
        {
        }
    }
    
  9. 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;
    }
    
  10. 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>();
    }        
    
  11. 运行该应用程序并导航至/api/values