在我的NinjectDependencyresolver
我有这个:
public NinjectDependencyResolver(IKernel kernelParam)
{
this.kernel = kernelParam;
AddBindings();
}
private void AddBindings()
{
kernel.Bind<IProductsRepository>().To<EFProductRepository>();
}
然后在我的controller
课程中我有这个:
public class ProductController : Controller
{
private IProductsRepository repository;
public int PageSize = 4;
public ProductController()
{
}
public ProductController(IProductsRepository productRepository)
{
this.repository = productRepository;
}
问题是repository
是null
此外,如果我向AddBinsings() method
添加一个断点,它在转到控制器之前不会被击中,controller
被击中但AddBindings()
没有。
这是否意味着我的Ninject
存在问题?
ALSO :收到此错误后我添加了parameter less constructor
ProductController
:
No parameterless constructor defined for this object
我认为我不需要那个构造函数,但是如果我删除它就会出现错误。
答案 0 :(得分:1)
我首先将构造函数移除到没有参数的ProductController。这将迫使ninject使用带有IProductsRepository的构造函数。
对于绑定部分,我们在NinjectWebCommon.cs文件中进行绑定。这是我们的样本:
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(new VBNinjectModule());
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
BindWebSpecificServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new VBNinjectDependencyResolver(kernel);
return kernel;
}
public static void BindWebSpecificServices(IKernel kernel)
{
kernel.Bind<IUserHelper>()
.To<UserHelper>()
.InRequestScope();
kernel.Bind<IRoleWebService>()
.To<RoleWebService>()
.InRequestScope();
}
答案 1 :(得分:0)
应该也在Gloabal.ashx.cs
档案中调用它