我是 ASP.NET Web API 的新手。
我已使用本教程将我的 ASP.NET MVC 3 项目升级到 ASP.NET MVC 4 。
现在我在这里尝试使用 Web Api,如您所见,我在这里尝试使用 ninject,但是当我ProductsController
以这种方式声明构造函数时,这不起作用。
public class ProductsController : ApiController
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
this._productService = productService;
}
public List<Product> GetProducts()
{
return _productService.GetAllProducts();
}
}
请帮助我。
如果我添加此构造函数,则没有调用 Web Api 方法,我通过使用断点确认了这一点,否则它会调用。浏览器显示一个 xml 错误,内容为
<Error><Message>An error has occurred.</Message></Error>
我的 NinjectWebCommon.cs 类代码是
[assembly: WebActivator.PreApplicationStartMethod(typeof(Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Web.App_Start.NinjectWebCommon), "Stop")]
namespace Web.App_Start
{
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <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);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IProductService>().To<ProductService>();
}
}
}