nhibernate : Repository Session Management

Posted by frosty on Stack Overflow See other posts from Stack Overflow or by frosty
Published on 2010-06-04T09:51:31Z Indexed on 2010/06/05 21:52 UTC
Read the original article Hit count: 296

Filed under:

At the moment my repository has 2 constructors. When i call these from my mvc website i am alway calling first constructor and thus opening a new session. Should i been passing in the session. How should i be doing this.

    public CompanyRepository()
    {
        _session = NHibernateHelper.OpenSession();
    }

    public CompanyRepository(ISession session)
    {
        _session = session;
    }




public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    var configuration = new Configuration();
                    configuration.Configure();
                    configuration.AddAssembly(typeof(UserProfile).Assembly);
                    configuration.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName,
                                              System.Environment.MachineName);
                    _sessionFactory = configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }

I'm using the Ninject IOC container ( very new to me ). I have the following container. How would i bind the ISession to the CompanyRepository.

 private class EStoreDependencies : NinjectModule
        {
            public override void Load()
            {
                Bind<ICompanyRepository>().To<CompanyRepository>();
                Bind<IUserProfileRepository>().To<UserProfileRepository>();
                Bind<IAddressRepository>().To<AddressRepository>();
                Bind<IRolesService>().To<AspNetRoleProviderWrapper>();
                Bind<IUserService>().To<AspNetMembershipProviderWrapper>();
                Bind<ICurrentUserSerivce>().To<DefaultCurrentUserSerivce>();
                Bind<IPasswordService>().To<AspNetMembershipProviderWrapper>();
                Bind<IStatusResponseRepository>().To<StatusResponseRepository>();
                Bind<ICategoryRepository>().To<CategoryRepository>();
                Bind<IProductRepository>().To<ProductRepository>();
            }
        }

© Stack Overflow or respective owner

Related posts about nhibernate