2016-04-27 37 views
0

我試圖使這項工作:充分利用SingleInstance分量PerRequest服務

builder.RegisterInstance(EngineFactory.Instance).SingleInstance().ExternallyOwned(); 
builder.Register(c => 
{ 
    EngineFactory engineFactory = DependencyResolver.Current.GetService<EngineFactory>(); 
    //EngineFactory engineFactory = c.Resolve<EngineFactory>(); 
    IEngineService engineService = engineFactory.GetService(); 
    return engineService; 
}).InstancePerRequest().As<IEngineService>(); 

而且我得到的錯誤:

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. 

爲了把事情說清楚,我想EngineFactory到是單身人士(這是外部創建的),IEngineService是Per(web)請求實例。

控制器屬性注入IEngineService時發生錯誤。

我不明白我在做什麼錯?

+0

你能分享異常的堆棧跟蹤嗎? –

回答

0

你舉報的代碼是正確的,AFAICT。

特別是:

// this is ok. 
builder.RegisterInstance(EngineFactory.Instance).SingleInstance().ExternallyOwned(); 

// you can use c.Resolve<EngineFactory>() and probably you should, 
// but really, is the same as your code 
builder.Register(c => c.Resolve<EngineFactory>().GetService()) 
    .InstancePerRequest().AsImplementedInterfaces(); 

你得到該錯誤消息是,你綁你IEngineService分辨率HTTP請求。在Autofac中,這是通過標記範圍進行管理的,即通過負責對象跟蹤和處理的容器進行管理。標記的作用域就是一個帶有名稱的作用域。

當使用InstancePerRequest時,Autofac會搜索一個名爲AutofacWebRequest的作用域,AutofacWebRequest會自動創建並通過Autofac/Asp.Net集成爲您處理,該集成可能未正確設置。

你的問題幾乎可以肯定地在Autofac/Asp.Net集成配置中。

因此,請參考guide on the website,並在出現問題時再次詢問。

最後一件事:如果你還沒有,請閱讀Autofac Lifetime Primer。如果你使用Autofac,這是純金。

編輯:偶然是你在Asp.Net核心?如果是這樣的話,here你可以找到一個不使用InstancePerRequest的註釋。