我正在尝试使用 Ninject 来管理对象的生命周期。对于我的 IRepository 对象,我需要实现 IDisposable,并且在 ConcreteRepository 中,我已经实现了 IDisposable 来终止我的 NHibernateSession。
我的问题是我还在 ConcreteRepository 中放置了一个静态变量来计算 ConcreteRepository 的实例化和销毁/处置的数量......当我运行应用程序时,我的数据库连接用完了,并且我的日志显示我的应用程序从未释放我的连接。
我的 Global.asax:
public class Global : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.DefaultNamespaces.Add("WebPortal.Controllers");
var log4netConfigFileInfo = new System.IO.FileInfo(Server.MapPath("~/log4net.xml"));
log4net.Config.XmlConfigurator.ConfigureAndWatch(log4netConfigFileInfo);
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Global));
log.Info("Started...");
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override Ninject.IKernel CreateKernel()
{
var kernel = new Ninject.StandardKernel(
new Utils.UtilsModule(),
new Web.DataObjects.NHibernate.DataObjectsNHibernateModule(),
new Payroll.PayrollModule(),
new Web.DataObjects.DbModule()
);
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
}
我用来测试的 Controller 模块:
public class DatabaseAreaModelModule
: NinjectModule
{
public override void Load()
{
Bind<DiscountEdit>().ToSelf().InRequestScope();
Bind<ItemCategoryEdit>().ToSelf().InRequestScope();
Bind<ItemEdit>().ToSelf().InRequestScope();
Bind<ModifierEdit>().ToSelf().InRequestScope();
Bind<ModifierSetEdit>().ToSelf().InRequestScope();
Bind<RevenueCenterEdit>().ToSelf().InRequestScope();
Bind<RevenueClassEdit>().ToSelf().InRequestScope();
Bind<TaxEdit>().ToSelf().InRequestScope();
}
}
我的“NHibernate”Ninject 模块:
public class DataObjectsNHibernateModule
: NinjectModule
{
public override void Load()
{
Bind<ISessionFactory>().ToProvider<NHibernateSessionProvider>().InSingletonScope();
Bind<IRepository>().To<NHibernateRepository>().InRequestScope();
}
}
我想弄清楚的是,为什么当我请求某个东西成为 InRequestScope() 时,它没有被处置……有什么想法吗?
最佳答案
为了在请求完成时获取要处理的 InRequestScope()
对象,您必须加载 OnePerRequestHttpModule
。
老实说,我不知道为什么每个人都觉得有必要以艰难的方式做事。只需从 nuget 安装 Ninject.MVC3,它就会为您处理所有这一切。我看到的 99.9% 的“请帮助我,Ninject 没有做它应该做的事”的问题是因为人们觉得有必要以艰难的方式做事,但他们做错了。
别让自己头疼了。只需安装 Ninject.MVC3 并将您的绑定(bind)和/或模块复制到 NinjectWebCommon.cs 即可。
关于c# - Ninject 3.0 不处理映射为 InRequestScope 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10593810/