Ninject.Web.Mvc 附加组件无法与 ASP.NET MVC 2 一起使用
我正在将 Ninject.Web.Mvc
(MVC 2 版本)附加组件与 ASP.NET MVC 2 一起使用。这是我的 Global.asax.cs
:
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes;
// RegisterAllControllersIn() is not available in the MVC 2 version of Ninject
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<IRepository>().To<NHibernateRepository>();
return kernel;
}
我还有一个基础 RepositoryController
:
public class RepositoryController : Controller
{
protected IRepository Repository { get; set; }
public RepositoryController()
{
}
public RepositoryController(IRepository repository)
{
Repository = repository;
}
}
如您所见,这是一个非常简单的设置,其中 RepositoryController
期望注入 IRepository< 的实例/code>,并且 Ninject 配置为使用
NHibernateRepository
的具体实例。但是,这不起作用,每当我尝试在控制器中访问它时,Repository
属性都为空。但是,如果我将代码更改为:
[Inject]
public IRepository Repository { get; set; }
那么它就可以正常工作。有谁知道为什么构造函数注入不起作用,但属性注入却起作用?
I'm using the Ninject.Web.Mvc
(the MVC 2 version) add-on with ASP.NET MVC 2. This is an excerpt of my Global.asax.cs
:
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes;
// RegisterAllControllersIn() is not available in the MVC 2 version of Ninject
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<IRepository>().To<NHibernateRepository>();
return kernel;
}
I also have a base RepositoryController
:
public class RepositoryController : Controller
{
protected IRepository Repository { get; set; }
public RepositoryController()
{
}
public RepositoryController(IRepository repository)
{
Repository = repository;
}
}
So as you can see, it's a very simple setup where RepositoryController
expects to be injected with an instance of an IRepository
, and Ninject is configured to use a concrete instance of NHibernateRepository
. However, this doesn't work and the Repository
property is null whenever I try to access it in a controller. However, if I change the code to this instead:
[Inject]
public IRepository Repository { get; set; }
Then it works fine. Does anyone know why constructor injection isn't working, but property injection is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试删除无参数构造函数。
Ninject 可能会选择错误的构造函数来解决。
为了测试它,您可以在两个构造函数中放置一个断点,看看哪一个会触发,但我有一种感觉,它是无参数的。
Try removing the parameterless constructor.
Ninject might be picking the wrong constructor to resolve.
To test it out, you could put a breakpoint in both constructors and see which one fires, but I have a feeling it's the parameterless one.