我有一个Aspnet Web API项目。我使用了存储库模式,我想使用ninject进行依赖项注入,但是它不起作用。
Ninject.Web.Common.cs
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ProjectName.API.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(ProjectName.API.App_Start.NinjectWebCommon), "Stop")]
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();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFirstService>().To<ServiceManager>().WithConstructorArgument("firstServiceDAL", new EFFirstDAL());
}
}
Ninject.Web.Common类是否正确?因为它不起作用。
我的api的响应;
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'FirstController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
FirstController.cs-我的控制器的构造函数
public class FirstController : ApiController
{
private readonly IFirstService _firstService;
public FirstController(IFirstService firstService)
{
this._firstService = firstService;
}
}
我该怎么办?
答案 0 :(得分:0)
似乎您没有公共的无参数构造函数。您的FirstController必须具有公共的无参数默认构造函数。 将以下代码添加到您的FirstController中。
public FirstController()
{
}
最好共享控制器。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFirstService>().To<FirstService>();
}