Setting up Fluent NHibernate and StructureMap for a web application

不羁岁月 提交于 2019-12-25 11:56:07

问题


I use this approuch http://www.kevinwilliampang.com/2010/04/06/setting-up-asp-net-mvc-with-fluent-nhibernate-and-structuremap/ for setting up fnh with structuremap but after one request I get the following exception

Session is closed! Object name: 'ISession'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ObjectDisposedException: Session is closed! Object name: 'ISession'.

My repository class looks like this:

public class Repository : IRepository {
    private readonly ISession _session;
    public Repository(ISession session) {
        _session = session;
    }
    public T Get<T>(Expression<Func<T, bool>> predicate) {
        return _session.CreateCriteria(typeof(T)).Add(predicate).UniqueResult<T>();
    }

and I register my repository in structuremap like this:

public class RepositoryRegistry : Registry {
    public RepositoryRegistry() {
        Scan(a => {
            a.AssembliesFromApplicationBaseDirectory();
            a.AddAllTypesOf<IRepository>();
        });
    }
}

How can I prevent the session from being closed?


回答1:


Are you registering your ISession the same way they do in the example? It should be HttpContext scoped like so:

      x.For<ISession>()
        .HttpContextScoped()
        .Use(context => context.GetInstance<ISessionFactory>().OpenSession());

The other possibility is that something is getting registered as a singleton (and is holding onto a closed session, rather than being recreated with the current session.

After seeing your question on the StructureMap list: http://groups.google.com/group/structuremap-users/browse_thread/thread/8023e0acc43ceeb3#, I see the problem.

You are injecting your repository into the sitemap, which is a singleton. So you will need to give the SiteMap a new session every request like so:

public class MvcSiteMapProvider : SiteMapProvider { 
     public static IRepository Repository { get; set; }; 
     public MvcSiteMapProvider() { }
} 

protected void Application_BeginRequest() { 
     MvcSiteMapProvider.Repository = ObjectFactory.GetInstance<ISession>();
}


来源:https://stackoverflow.com/questions/3833243/setting-up-fluent-nhibernate-and-structuremap-for-a-web-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!