asp.net-mvc - 在 Asp.Net MVC 应用程序中使用 Structuremap 将 ISession 注入(inject)我的存储库

标签 asp.net-mvc nhibernate fluent-nhibernate structuremap

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

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

在 Asp.Net MVC 应用程序中,使用 StructureMap,我将如何在 StructureMap 注册表中设置 ISession?我是否还需要将 SessionFactory 添加到容器中? FluentNHibernate 会改变什么吗?

最佳答案

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

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

实现 ISession 和 ISessionFactory 接口(interface)(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(SessionFactoryAggreagator),任何DI框架都可以轻松解析ISession。

如果你的 DI 不支持工厂方法(我不知道 Structure Map 是否支持),这很好。

我已将这些实现添加到我的 Commons 程序集中,因此我不应该每次都重新实现它。

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

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

代码可能如下所示:

// The Registry in StructureMap
ForRequestedType<ISessionFactory>()
        .CacheBy(InstanceScope.Singleton)
        .TheDefaultIsConcreteType<SessionFactoryAggregator>();

ForRequestedType<ISession>()
        .CacheBy(InstanceScope.Hybryd)
        .TheDefaultIsConcreteType<SessionAggregator>();

// Then in EndRequest call
HttpContextBuildPolicy.DisposeAndClearAll()

关于asp.net-mvc - 在 Asp.Net MVC 应用程序中使用 Structuremap 将 ISession 注入(inject)我的存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1296901/

相关文章:

nhibernate - 使用按位运算符时 HQL 到 CriteriaQuery

c# - 具有多个结果集的 NHibernate 存储过程

c# - Fluent NHibernate - 查询派生类

c# - .Net Core RC2 MVC 参数在 Controller 中为空

c# - 使用 Html Helper 在创建的 TextBox 元素中添加新的 html 属性

c# - 避免来自 ASP.NET 中的 View 的双重请求的最佳实践

c# - 如何使用流畅的 nhibernate 自动映射在同一个表中引用父实体?

nhibernate - 如何从 ISessionFactory 获取 NHibernate 配置

c# - nHibernate HQL - 实体未映射

asp.net-mvc - T4MVC 3.7.4 在 VS 2013 中不起作用(在 VS 2012 中它工作得很好)