【发布时间】:2010-03-01 18:41:10
【问题描述】:
我有一个使用 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.
}
}
... //global.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 继承的页面的页面加载 - 无论先出现的情况)。
【问题讨论】: