2015-11-13 35 views
0

我用Fluent Nhibernate使用Simple Injector。我所記錄的「會話」中SimpleInjectorInitializer文件用下面的代碼:Simple Injector + Fluent Nhibernate with UnitOfWork

var container = Bootstrapper. 

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

然而,在會話是通過我的建設者「的UnitOfWork,」她被註冊,總有「會話」的一個實例活動的,在處理對象時會導致一些錯誤,因爲「具有相同標識符值的不同對象已經與會話相關聯」。 如何使用Nhiberante UnitOfWork工作「會話」以避免此問題?

+0

您可能要修改你的問題,並添加額外的細節(如作爲堆棧跟蹤信息和使用情況),因爲您的問題目前過於寬泛,並且不清楚確切問題是什麼。 – Steven

+0

我解決... 我改進了我的架構,豐富了我的領域,減少了「控制器」的職責,讓服務保持協商和解決問題。因爲我使用AutoMapper來操作導致此錯誤的DTO par Model對象。 –

回答

1

我遇到了這個問題,同時尋找一個解決方案,使用簡單注射器與流利nhibernate(從Ninject切換到簡單注射器時)。這個例子不使用工作單元模式,因爲真的nHibernate的會話工作單位容器。這是它是如何做(ASP.NET MVC exmple)

SessionProvider

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));