我已经阅读了我能找到的每个Stack Overflow问题,但无济于事。当我通过NuGet安装Ninject包时,没有安装NinjectWebCommon.cs类,所以我自己编写了代码(下面)。我安装了Ninject,Ninject.WebCommon,Ninject.Webcommon.Webhost,Ninject.WebApi,Ninject.WebApi.DependencyResolver。但是,我在控制器中得到了众所周知的消息,我必须有一个无参数控制器,当然我不想要,因为我想要DI。
这是我创建的Ninject类:
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);
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(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.Load(Assembly.GetExecutingAssembly());
kernel.Bind<IUnitsSL>().To<UnitsSL>();
kernel.Bind<IForecastLogic>().To<ForecastLogic>();
kernel.Bind<IForecastRepositoryAsync>().To<ForecastRepositoryAsync>();
}
}
这是控制器
namespace ForecastApi.Controllers
{
public class ForecastController : ApiController
{
private IUnitsSL _serviceLayer { get; set; }
private readonly IForecastLogic _forecastLogic;
public ForecastController(IForecastLogic forecastLogic)
{
_forecastLogic = forecastLogic;
_serviceLayer = new UnitsSL();
}
[Route("projection")]
[HttpPost]
public async Task<IHttpActionResult> GetDemandForecast([FromBody]
ProjectionRequestModel model)
{
var retVal = await _forecastLogic.GetDemandForecastData(model);
return Ok(retVal);
}
}
通过Postman测试时错误消息的确切措辞是:尝试创建“ForecastController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。“
如果有帮助,我正在模拟我的业务调用单元测试,他们正在使用Ninject库和Moq。它似乎是失败的构造函数。
TIA
答案 0 :(得分:0)
无论出于何种原因,完全卸载Ninject并重新安装它(这是版本3.3)解决了这个问题。如果其他人有类似问题,请留在此处。我最初安装了
当我卸载所有这些软件包,然后再次重新安装它们v3.3时,NinjectWebCommon.cs文件被添加并且一切正常。我只能假设当我推出自己的公共文件以弥补Ninject没有安装它时,有些东西丢失了。