我有一个使用 Ninject 2.0 的 ASP.NET 3.5 WebForms 应用程序。但是,尝试使用 Ninject.Web 扩展来提供对 System.Web.UI.Page 的注入,即使我切换到使用服务定位器来提供引用(使用 Ninject ),没有问题。
我的配置(为简单起见简化):
public partial class Default : PageBase // which is Ninject.Web.PageBase
{
[Inject]
public IClubRepository Repository { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
var something = Repository.GetById(1); // results in null reference exception.
}
}
...
//全局.asax.cs
public class Global : Ninject.Web.NinjectHttpApplication
{
/// <summary>
/// Creates a Ninject kernel that will be used to inject objects.
/// </summary>
/// <returns>
/// The created kernel.
/// </returns>
protected override IKernel CreateKernel()
{
IKernel kernel =
new StandardKernel(new MyModule());
return kernel;
}
..
...
public class MyModule : NinjectModule
{
public override void Load()
{
Bind<IClubRepository>().To<ClubRepository>();
//...
}
}
通过服务定位器获取 IClubRepository 具体实例效果很好(使用相同的“MyModule”)。 IE。
private readonly IClubRepository _repository = Core.Infrastructure.IoC.TypeResolver.Get<IClubRepository>();
我缺少什么?
[更新]终于回到了这一点,它可以在经典管道模式下工作,但不能在集成模式下工作。是否需要经典管道?
[更新 2] 连接我的 OnePerRequestModule 是问题(为了清楚起见,在上面的示例中已将其删除):
protected override IKernel CreateKernel()
{
var module = new OnePerRequestModule();
module.Init(this);
IKernel kernel = new StandardKernel(new MyModule());
return kernel;
}
...需要是:
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new MyModule());
var module = new OnePerRequestModule();
module.Init(this);
return kernel;
}
因此解释了为什么我在集成管道下遇到空引用异常(对于 Ninject 注入的依赖项,或者只是从 Ninject.Web.PageBase 继承的页面的页面加载 - 无论先发生什么)。