【问题标题】:Simple Injector + Fluent Nhibernate wiith UnitOfWork简单的注射器 + Fluent Nhibernate 与 UnitOfWork
【发布时间】:2015-12-08 08:14:23
【问题描述】:

我正在使用带有 Fluent Nhibernate 的 Simple Injector。我使用以下代码在 SimpleInjectorInitializer 文件中记录了“会话”:

var container = Bootstrapper.

container.Register(() => Core.Core.Dados.NH.NhSessionFactory.Current.OpenSession(),
    new SimpleInjector.Integration.Web.WebRequestLifestyle());

但是,会话是通过我的“UnitOfWork”中的构建器注册的,始终有一个“会话”实例处于活动状态,在处理对象时导致一些错误,作为“具有相同标识符的不同对象值已与会话关联“。 如何使用 Nhiberante UnitOfWork 进行“会话”以避免此问题?

【问题讨论】:

  • 您可能需要重新表述您的问题并添加其他详细信息(例如堆栈跟踪信息和用法),因为您的问题目前过于宽泛,并且不清楚确切的问题是什么。
  • 我解决...我改进了我的架构,丰富了我的领域并减少了“控制器”的职责,让服务保持咨询和替代。因为我是使用 AutoMapper 来操作 DTO par Model 对象,导致了这个错误。

标签: c# session nhibernate unit-of-work simple-injector


【解决方案1】:

我在寻找将 Simple Injector 与 Fluent nhibernate 结合使用的解决方案时遇到了这个问题(从 Ninject 切换到 Simple Injector 时)。这个例子没有使用 Unit Of Work 模式,因为 nHibernate 的 Session Unit of Work 容器。这就是它的实现方式(ASP.NET MVC 示例)

会话提供者

public class SessionProvider
{
    private readonly string _connectionString;
    private ISessionFactory _sessionFactory;

    public ISessionFactory SessionFactory
    {
        get { return _sessionFactory ?? (_sessionFactory = CreateSessionFactory()); }
    }

    public SessionProvider(string connectionString)
    {
        _connectionString = connectionString;
    }

    private ISessionFactory CreateSessionFactory()
    {

       return Fluently.Configure()
                    .Database(SQLiteConfiguration.Standard.ConnectionString(_connectionString)
                    .Driver<ProfiledSQLiteClientDriver>)
                    .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                    .ExposeConfiguration(cfg => cfg.Properties.Add("use_proxy_validator", "false"))
                    .BuildSessionFactory();
    }
}

Global.asax.cs

        var sessionProvider = new SessionProvider(ConfigurationManager.ConnectionStrings["sqlite"].ConnectionString);

        var container = new SimpleInjector.Container();
        container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

        container.Register(typeof(IRepository<>), new[] { typeof(Repository<>).Assembly });
        container.RegisterSingleton<ICommandDispatcher>(new CommandDispatcher(container));
        container.Register(typeof(ICommandHandler<>), new[] { typeof(UserCommandsHandler).Assembly });
        /* here comes Session wiring ....*/
        container.Register(() => sessionProvider.SessionFactory, Lifestyle.Singleton);
        container.Register<ISession>(()=> container.GetInstance<ISessionFactory>().OpenSession(), Lifestyle.Scoped);

        container.Verify();
        DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 2011-02-05
    • 2012-04-03
    相关资源
    最近更新 更多