代码之家  ›  专栏  ›  技术社区  ›  mxmissile

在Asp.NETMVC应用程序中使用Structuremap将ISession注入我的存储库

  •  4
  • mxmissile  · 技术社区  · 15 年前

    我的存储库都在构造函数中使用ISession:

    protected Repository(ISession session)
    {
         this.session = session;
    }
    private readonly ISession session;
    

    2 回复  |  直到 15 年前
        1
  •  1
  •   Alex    12 年前

    您应该使用工厂方法注册ISession。

    另一个选择(并非总是最好的,但易于使用)是:

    实现ISession和ISessionFactory接口(SessionProxy和SessionFactoryProxy)。

    public class SessionAggregator : ISession {
        protected ISession session;
    
        public SessionAggregator(ISessionFactory theFactory) {
            if (theFactory == null)
                throw new ArgumentNullException("theFactory", "theFactory is null.");
            Initialise(theFactory);
        }
    
        protected virtual void Initialise(ISessionFactory factory) {
            session = factory.OpenSession();
        }
        // the ISession implementation - proxy calls to the underlying session  
     }
    
    public class SessionFactoryAggregator : ISessionFactory {
        protected static ISessionFactory factory;
        private static locker = new object();
        public SessionFactoryAggregator() {
                if (factory == null) {
                  lock(locker) {
                    if (factory == null)
                      factory = BuildFactory();
                  }
                }
        }
    
        // Implement the ISessionFactory and proxy calls to the factory                
    }
    

    通过这种方式,您可以只注册ISession(由SessionAggregator实现)和ISessionFactory(SessionFactoryAggregator),任何DI框架都可以轻松地解析ISession。

    我已经将这些实现添加到我的Commons assembly中,所以我不应该每次都重新实现它。

    编辑: 现在,要在web应用程序中使用ISession:

    1. 在结构映射中注册SessionFactoryAggregator(生命周期可以是单例的)。
    2. 在Snstrucure映射中注册SessionAggregator,并将其生存期设置为InstanceScope.Hybrid。
    3. 在每个请求结束时,您需要调用HttpContextBuildPolicy.DisposeAndClearAll()来处理会话

    // The Registry in StructureMap
    ForRequestedType<ISessionFactory>()
            .CacheBy(InstanceScope.Singleton)
            .TheDefaultIsConcreteType<SessionFactoryAggregator>();
    
    ForRequestedType<ISession>()
            .CacheBy(InstanceScope.Hybryd)
            .TheDefaultIsConcreteType<SessionAggregator>();
    
    // Then in EndRequest call
    HttpContextBuildPolicy.DisposeAndClearAll()
    
        2
  •  0
  •   Community CDub    7 年前

    This 问题及;答案可能会帮助你。

    一种方法-从中窃取nhibernate会话管理 "S#arp Architecture"