我遇到麻烦,制作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
答案 0 :(得分:11)
以下是我为您编写的一些步骤,可以帮助您入门:
Microsoft.AspNet.WebApi
和Ninject.MVC3
定义界面:
public interface IRepository
{
string GetData();
}
并实施:
public class InMemoryRepository : IRepository
{
public string GetData()
{
return "this is the data";
}
}
添加API控制器:
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
。