2014-05-15 40 views
0

我很確定我錯過了一個非常基本和簡單的事情。Autofac WebApi集成與MultiTenant容器不兼容

我使用Autofac和它的如下

var builder = new ContainerBuilder(); 
// Registratino of modules here 
var container = builder.Build(); 

var tenantStrategy = new AppSettingsTenantIdentifier(appSettings); 
var mtc = new MultitenantContainer(tenantStrategy, container); 

//這裏租戶特定模塊登記

變種解析器=新AutofacWebApiDependencyResolver(MTC)的多租戶容器;

GlobalConfiguration.Configuration.DependencyResolver = resolver;

這被稱爲Application_Start。經過上面的叫,我嘗試註冊類解決一個如下

var webApiConfig = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof (WebApiConfig)) as WebApiConfig; 

一個這個類的依賴關係被註冊爲InstancePerAPiRequest的。在這一點上,我得到以下錯誤。

No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself. 

我不知道我怎樣才能解決這個問題。我知道我可以用標記AutofacWebRequest創建一個新的生命週期範圍,然後使用該生命週期範圍來解決,但這對我來說並不合適。

+0

假設WebApiConfig是Web API的默認類,它是靜態的。爲什麼你需要通過容器解決它? –

+0

我們必須更改該類,因爲我們爲不同的客戶端配置了不同的路由。 – Suhas

回答

1

如果您註冊了InstancePerRequestInstancePerApiRequest,那麼您無法在請求之外解決它。

如果您需要在請求生命週期(實際API請求之外)之外解析依賴關係,請爲其選擇不同的生命週期。 InstancePerLifetimeScope非常接近InstancePerApiRequest,並且也將按照每個請求進行工作。

但要注意:如果解決了一些從容器的要求之外,它是IDisposable那麼對象將堅持圍繞應用程序的生命週期,因爲Autofac將保留,並設法處理它。如果你不瞭解這種行爲,這可能是一個緩慢的內存泄漏。 You can read more about that on the Autofac wiki.

+0

鏈接更新:http://autofac.readthedocs.org/en/latest/lifetime/disposal.html關於確定性處置 – Nordes