我被利用AutoFac的ServiceHost.AddDependencyInjectionBehavior()
擴展(如Autofac documentation描述)注入業務層爲自託管(InstanceContextMode =每個呼叫)WCF服務Autofac自託管的WCF服務和對象的處置
我的業務層使用的組件每次有新的請求進入時都不能重新創建(假設它需要持久的數據庫連接)。
因此,構建容器時,我想作爲一個實例,即:註冊BL服務
builder.RegisterType<BusinessLayer>()
.SingleInstance();
業務層注入WCF服務工作正常;我的問題是:
Dispose()不會在容器中創建的任何服務上調用:不僅僅是業務層本身,也是'持久'服務。
我預計這會發生在BL服務本身。從Autofac docs再次:
如果你有單組分(註冊SingleInstance()),他們將住在集裝箱的生活。由於容器使用壽命通常是應用程序的使用壽命,這意味着組件 將不會在應用程序結束前處理。
,偏偏沒有我的「孩子」(Autofac註冊)服務(即「IPersistentService」下面)的處置時的壽命範圍 - 因爲我不是明確地讓他們「SingleInstance 「? 備註::如果我在關閉ServiceHost後手動處理業務層服務,仍然是這種情況
E.g. (略去了IDisposable的實現):
[ServiceContract]
public interface IMyService
{
void DoStuff();
}
public class MyService : IMyService
{
IBusinessLayer _bl;
public MyService(IBusinessLayer bl)
{
_bl = bl;
}
public void DoStuff()
{
_bl.BLDoStuff();
}
}
public interface IBusinessLayer
{
void BLDoStuff();
}
public class BusinessLayer : IBusinessLayer
{
IPersistentService _service;
public BusinessLayer(IPersistentService service)
{
_service = service;
}
public void BLDoStuff()
{
// Do something that requires a 'cached'/persistent component
_service.DoSomethingWithPersistentConnection();
}
}
public interface IPersistentService : IDisposable
{
void DoSomethingWithPersistentConnection();
}
隨着Autofac註冊看起來像:
builder.RegisterType<BusinessLayer>()
.SingleInstance();
builder.RegisterType<MyPersistentService>()
.As<IPersistentService>()
.OnActivated(e => e.Instance.Start());
「爲什麼我的'孩子'(Autofac註冊的)服務(即下面的'IPersistentService')沒有一個在終生範圍是」時處理「。這個問題通常被稱爲[Captive Dependency](俘虜依賴)(http://blog.ploeh.dk/2014/06/02/captive-dependency/)。 – Steven
沒錯。葉,這解釋了它 - 並感謝與該描述的鏈接。 – Ive