2016-11-09 76 views
2

我試圖讓一個事務ID用於在整個請求中進行日誌記錄。 Trasaction ID是AuditContext中的一個屬性,每個請求都是單身。我在Global.asax.cs中有以下代碼手動解析InstancePerRequest類型時未收到Autofac相同的注入實例

builder.RegisterType<AuditContext>().As<IAuditContext>().InstancePerRequest(); 
.... 
GlobalContainer = builder.Build(); 
config.DependencyResolver = new AutofacWebApiDependencyResolver(GlobalContainer); 

事務ID在基類api類中設置。

public BaseApiController(IAuditContext auditContext, IDispatcher dispatcher = null) 
{ 
    auditContext.TransactionID = Guid.NewGuid().ToString(); 
} 

具有正確事務標識的AuditContext對象被注入,在下面的構造函數注入用法中。

public class SapEventLogger : ISapEventLogger 
{   
    private IAuditContext auditContext;   

    public SapEventLogger(IAuditContext auditContext) 
    { 
     this.auditContext = auditContext; //this auditContext object has correct transaction ID 
    } 

} 

如果有任何異常,我想檢索事務ID並記錄它。但是當我嘗試手動解析時,我得到一個新的AuditContext對象,其中事務標識爲空。

public class ServiceExceptionHandler : ExceptionHandler 
{ 
    public override void Handle(ExceptionHandlerContext context) 
    { 
     using (var scope = GlobalContainer.BeginLifetimeScope(Autofac.Core.Lifetime.MatchingScopeLifetimeTags.RequestLifetimeScopeTag)) 
     { 
      var auditContext = scope.Resolve<FDP.Services.Common.IAuditContext>(); 
      transactionID = auditContext.TransactionID; //Transaction ID is null here 
     } 
    } 
} 

不確定爲什麼在手動解析AuditContext時創建新對象。我錯過了什麼嗎?

回答

0

通過BeginLifetimeScope呼叫,您可以手動創建第二個請求生存期,而不是使用現有的請求生存期。兩個請求生存期等於兩個實例。

The solution to this is outlined in the Autofac docs in more detail但短期的版本是得到從請求消息的請求生命週期中的處理程序方面:

// Get the request lifetime scope so you can resolve services. 
var requestScope = context.Request.GetDependencyScope(); 

// Resolve the service you want to use. 
var auditContext = requestScope.GetService(typeof(IAuditContext)) as IAuditContext; 

// Do the rest of the work in the filter. 
auditContext.DoWork(); 
+0

謝謝@Travis!還有一個疑問。如果將AuditContext註冊爲InstancePerLifetimeScope,是否可以在ActionContext(請求)不可用的Web Api Controller範圍之外手動解析它?如果解析不是Web API請求的一部分,則可以返回null。 – Baga

+0

如果您可以獲取終身範圍所在的Web API請求消息,則表示您很好。如果你不能,你就卡住了。就這麼簡單。 –

+0

哦,如果你註冊了每個請求的實例並且在請求之外解析,你會得到一個異常,而不是null。 –

相關問題