【发布时间】:2011-07-19 04:55:06
【问题描述】:
我有一个像这样的 Ninject 和 NHibernate 设置。现在,如果我有这种情况..
class HomeController : Controller
{
[Inject]
public ISession Session { get; set; }
}
这可以正常工作。
但是如果我再上一堂课……
class QueryObject
{
[Inject]
public ISession Session { get; set; }
}
// .. somewhere else in my program.
var test = new QueryObject().Execute();
ISession 为空!这不仅适用于 ISession,而且适用于我尝试注入的任何内容。
这是我的 SessionModule:
public class SessionModule : Ninject.Modules.NinjectModule
{
private static ISessionFactory sessionFactory;
public override void Load()
{
Bind<ISessionFactory>()
.ToMethod(c => CreateSessionFactory())
.InSingletonScope();
Bind<ISession>()
.ToMethod(c => OpenSession())
.InRequestScope()
.OnActivation(session =>
{
session.BeginTransaction();
session.FlushMode = FlushMode.Commit;
})
.OnDeactivation(session =>
{
if (session.Transaction.IsActive)
{
try
{
session.Transaction.Commit();
}
catch
{
session.Transaction.Rollback();
}
}
});
}
/// <summary>
/// Create a new <see cref="NHibernate.ISessionFactory"/> to connect to a database.
/// </summary>
/// <returns>
/// A constructed and mapped <see cref="NHibernate.ISessionFactory"/>.
/// </returns>
private static ISessionFactory CreateSessionFactory()
{
if (sessionFactory == null)
sessionFactory = Persistence.SessionFactory.Map
(System.Web.Configuration
.WebConfigurationManager
.ConnectionStrings["Local"]
.ConnectionString
);
return sessionFactory;
}
/// <summary>
/// Open a new <see cref="NHibernate.ISession"/> from a <see cref="NHibernate.ISessionFactory"/>.
/// </summary>
/// <returns>
/// A new <see cref="NHibernate.ISession"/>.
/// </returns>
private static ISession OpenSession()
{
// check to see if we even have a session factory to get a session from
if (sessionFactory == null)
CreateSessionFactory();
// open a new session from the factory if there is no current one
return sessionFactory.OpenSession();
}
}
【问题讨论】:
-
NB 一般而言,查询对象(与一般实体一样)首先不应该有这样的依赖关系
标签: ninject