开发者

Does StructureMap have scoping corresponding to NInject's DefinesNamedScope/InNamedScope?

开发者 https://www.devze.com 2023-02-14 08:26 出处:网络
The problem I\'d like to solve is sharing an ISessionProvider between IXyzRepositories (where ISess开发者_如何学JAVAionProvider holds the current NHibernate ISession).

The problem I'd like to solve is sharing an ISessionProvider between IXyzRepositories (where ISess开发者_如何学JAVAionProvider holds the current NHibernate ISession).

I'm tweaking the "Setting up session per presenter" recipe from NHibernate 3 Cookbook, and would like to keep StructureMap (brownfield project).


I think you would have to create a custom Lifecyle to do that, although I am not sure what exactly you are trying to accomplish...

To create a custom Lifecycle, you just have to implement the ILifecycle interface and the use it in your registration. Here is an example you can look at: http://blog.mikeobrien.net/2010/01/creating-structuremap-lifecycle-for-wcf.html.


In a web application I use Singleton for the sessionFactory and HybridHttpOrThreadLocalScoped for the session: This is my structuremap registry:

public class NhibernateRegistry: Registry
{
    public NhibernateRegistry()
    {
        For<ISessionFactory>()
        .Singleton()
        .Use(new NHibernateSessionFactory(connectionString).SessionFactory);

        For<ISession>()
        .HybridHttpOrThreadLocalScoped()
        .Use(o => o.GetInstance<ISessionFactory>().CurrentSession);
    }
}

My NHibernateSessionFactory is similar to SessionProvider class used in the book. Everything is disposed at the end of the request (web app):

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

I use a generic repository:

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private readonly ISession _session;

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

    public T Load(Guid Code)
    {
        return (_session.Load<T>(Code));
    }

}

but you can easily change it with your own implementation. I register the repository here:

public class RepositoriesRegistry : Registry
{
    public RepositoriesRegistry()
    {
        For <Data.IRepository<Domain.Reminder, Guid>>()
            .HybridHttpOrThreadLocalScoped()
            .Use<Data.NH.Repository<Domain.Reminder, Guid>>();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消