Dmi*_*ryL 7 c# ninject .net-4.0 asp.net-mvc-3
我遇到了麻烦,制作了Ninject和WebAPI.All合作.我将更加具体:
首先,我玩了WebApi.All包,看起来它对我来说很好.
第二,我加入RegisterRoutes的Global.asax下一行:
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
Run Code Online (Sandbox Code Playgroud)
所以最终的结果是:
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());
}
Run Code Online (Sandbox Code Playgroud)
一切似乎都很好,但是当我试图将用户重定向到特定的操作时,例如:
return RedirectToAction("Index", "Home");
Run Code Online (Sandbox Code Playgroud)
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());
}
Run Code Online (Sandbox Code Playgroud)
现在重定向工作正常,但是当我尝试访问我的API操作时,我得到错误告诉我
Ninject couldn't return controller "api"哪个是绝对合乎逻辑的,我没有这样的控制器.
我确实搜索了一些如何使Ninject与WebApi一起工作的信息,但我找到的所有内容仅适用于MVC4或.Net 4.5.由于技术问题,我无法将我的项目转移到新平台,所以我需要为这个版本找到一个可行的解决方案.
这个答案看起来像一个有效的解决方案,但是当我尝试启动项目时,我得到编译器错误
CreateInstance = (serviceType, context, request) => kernel.Get(serviceType);Run Code Online (Sandbox Code Playgroud)
告诉我:
System.Net.Http.HttpRequestMessage is defined in an assembly that is not referenced
关于在汇编中添加refference的事情
System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
我不知道接下来要做什么,我在.NET 4和MVC3上找不到关于ninject和webapi的任何有用信息.任何帮助,将不胜感激.
Dar*_*rov 11
以下是我为您编写的几个步骤,可以帮助您入门:
Microsoft.AspNet.WebApi和Ninject.MVC3定义一个接口:
public interface IRepository
{
string GetData();
}
Run Code Online (Sandbox Code Playgroud)并实施:
public class InMemoryRepository : IRepository
{
public string GetData()
{
return "this is the data";
}
}
Run Code Online (Sandbox Code Playgroud)添加API控制器:
public class ValuesController : ApiController
{
private readonly IRepository _repo;
public ValuesController(IRepository repo)
{
_repo = repo;
}
public string Get()
{
return _repo.GetData();
}
}
Run Code Online (Sandbox Code Playgroud)在您的注册API路线Application_Start:
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 }
);
}
Run Code Online (Sandbox Code Playgroud)使用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()
{
}
}
Run Code Online (Sandbox Code Playgroud)在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;
}
Run Code Online (Sandbox Code Playgroud)在RegisterServicesmethod(~/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>();
}
Run Code Online (Sandbox Code Playgroud)运行应用程序并导航到/api/values.