2012-02-18 12 views
1

我得到以下異常「無法解析實例,並且無法從此LifetimeScope中創建嵌套生命期,因爲它已被處置。」當我嘗試從global.asax Application_EndRequest事件解析對象時。我用Autofac在版本2.5.2.830autofac與asp.net webforms實例無法解析和嵌套生命期不能爲

public class Global : System.Web.HttpApplication, IContainerProviderAccessor 
{ 
    // Provider that holds the application container. 
    static Autofac.Integration.Web.IContainerProvider _containerProvider; 

    // Instance property that will be used by Autofac HttpModules 
    // to resolve and inject dependencies. 
    public Autofac.Integration.Web.IContainerProvider ContainerProvider 
    { 
     get { return _containerProvider; } 
    } 
    protected void Application_Start(object sender, EventArgs e) 
    { 
     var builder = new ContainerBuilder(); 
... 
     _containerProvider = new ContainerProvider(builder.Build()); 
    } 

    protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     ISession session = _containerProvider.RequestLifetime.Resolve<ISession>(); 
     session.BeginTransaction(); 
    } 

    private void Application_EndRequest(object sender, EventArgs e) 
    { 
     ISession session = ContainerProvider.RequestLifetime.Resolve<ISession>(); 
    } 

我以這種方式登記:。

builder.Register(X => x.Resolve()的openSession())作爲()InstancePerHttpRequest() ; }

+0

爲什麼要在EndRequest中解析會話?你打算在那裏結束會議嗎? – 2012-02-18 12:11:57

+0

是的,我想提交交易和關閉會話。我嘗試使用autofac創建會話預先請求模式。 – 2012-02-18 12:55:08

回答

5

Autofac通過名爲Autofac.Integration.Web.ContainerDisposalModule的HttpModule處理會話。

你需要或者

  • 把自己的會話清理被容器處置前運行模塊中。 這可能是一個問題,因爲HttpModules的順序不能保證。

OR

  • 從web.config中取出容器處置的HttpModule,做你自己的一生範圍的清理你的應用EndRequest
private void Application_EndRequest(object sender, EventArgs e) 
{ 
    ISession session = ContainerProvider.RequestLifetime.Resolve(); 
    //cleanup transaction etc... 
    ContainerProvider.EndRequestLifetime();  
}

OR

  • 創建一個會話管理器類是IDisposable和生命週期的範圍,把你的ISession作爲構造函數的依賴關係,並在你的會話清理結束時處理一生。

    public class SessionManager : IDisposable 
    { 
     private readonly ISession _session; 
     private ITransaction _transaction; 

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

     public void BeginRequest() 
     { 
      _transaction = _session.BeginTransaction(); 
     } 

     #region Implementation of IDisposable 

     /// 
     /// Dispose will be called automatically by autofac when the lifetime ends 
     /// 
     public void Dispose() 
     { 
      //commit rollback, whatever 
      _transaction.Commit(); 
     } 

     #endregion 
    } 

您必須確保初始化會話管理器。


    protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     SessionManager manager = _containerProvider.RequestLifetime.Resolve(); 
     manager.BeginRequest(); 
    } 
+0

+1。謝謝,這是我需要的。 – 2012-02-25 18:13:14

+0

很好的解釋和一個很好的方法! – 2015-07-15 20:29:34