在NHibernate BeginTransaction上获取null异常

时间:2013-10-03 05:01:47

标签: c# nhibernate fluent-nhibernate ninject

我有一个使用nhibernate的Windows服务应用程序,我使用了ninject来初始化Isession。

    [STAThread]
    public static void Main(string[] args)
    {
        using (IKernel kernel = CreateKernel())
        {
            HostFactory.Run(x =>
            {
                x.BeforeStartingServices(c =>
                                             {
                                                 XmlConfigurator.Configure();
                                                 SetAdoNetAppenderConnectionStrings("DefaultConnection");
                                             });

                x.Service<IService>(c =>
                {
                    c.SetServiceName(BindingName);
                    c.ConstructUsing(s => kernel.Get<IIntraClockAuctionService>());
                    c.WhenStarted(s => s.Start());
                    c.WhenStopped(s => s.Stop());
                    c.WhenPaused(s => s.Pause());
                    c.WhenContinued(s => s.Continue());
                });

                // Default run mode, change this to provide different credentials
                x.RunAsLocalSystem();

                x.DependsOnEventLog();
                x.DependsOnMsSql();

                x.SetDescription(Description);
                x.SetDisplayName(DisplayName);
                x.SetServiceName(ServiceName);
            });
        }
    }

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();

        kernel.Bind<ISessionFactory>().ToProvider<SessionFactoryBuilder>().InSingletonScope();
        kernel.Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession())
            .InCallScope();
        kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>));

        kernel.Bind<IJobFactory>().To<JobFactory>();
        kernel.Bind<Func<Type, IJob>>().ToConstant(new Func<Type, IJob>(type => (IJob)kernel.Get(type)));
        kernel.Bind<ISchedulerFactory>().ToConstant(new StdSchedulerFactory(GetQuartzProperties()));
        kernel.Bind<JobManager>().ToSelf().InSingletonScope();

        return kernel;
    }

我有开始交易的会话

public static class SessionTransaction
{
    public static void BeginTransation(ISession session)
    {
        session.FlushMode = FlushMode.Commit;
        session.BeginTransaction();
    }        

    public static void CommitTrans(ISession session)
    {
        try
        {
            session.Transaction.Commit();
        }
        catch (Exception e)
        {
            session.Transaction.Rollback();
            throw;
        }            
    }
} 

我有以下交易代码

public class StartJob : IJob
{
    private readonly ISession _session;
    private readonly JobManager _jobManager;

    public AuctionRegistrationStartJob(ISession session, JobManager jobManager)
    {
        _session = session;
        _jobManager = jobManager;
    }

    public void Execute(IJobExecutionContext context)
    {
            SessionTransaction.BeginTransation(_session);
           //Code to select/insert/update etc   
            SessionTransaction.CommitTrans(_session);

    }
}

但有时候我得到null异常

NullReferenceException未将对象引用设置为对象的实例。 at NHibernate.Transaction.AdoTransaction.Begin(IsolationLevel isolationLevel)at NHibernate.Transaction.AdoTransaction.Begin()at NHibernate.Impl.SessionImpl.BeginTransaction()

Windows服务线程中的会话是否可能为空?

如果会话为空,我是否需要OpenSession?

这是一个流利的nhibernate配置

        var config =
            Fluently.Configure()
            .Database(dbType.ConnectionString(connectionString))
            .Cache(c => c.UseQueryCache().UseSecondLevelCache().UseMinimalPuts()
                .ProviderClass<SysCacheProvider>())
            //.ExposeConfiguration(x => x.SetProperty("current_session_context_class", "web"))
            .Mappings(m =>
            {
                m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
                m.AutoMappings.Add(
                    // custom automapping configuration - map classes in models assembly
                    AutoMap.Assemblies(new CustomAutoMap(), new[] {Assembly.GetExecutingAssembly()})
                );
            });

0 个答案:

没有答案