2015-09-28 56 views
0

我試圖在ServiceStack中使用MEF作爲ContainerAdapter(https://github.com/ServiceStack/ServiceStack/wiki/The-IoC-container)。在ServiceStack服務中使用MEF

我做了ContainerAdapter:

internal class MefIocAdapter : IContainerAdapter 
{ 
    private readonly CompositionContainer _container; 

    internal MefIocAdapter(CompositionContainer container) 
    { 
     _container = container; 
    } 

    public T TryResolve<T>() 
    { 
     return _container.GetExportedValue<T>(); 
    } 

    public T Resolve<T>() 
    { 
     return _container.GetExportedValueOrDefault<T>(); 
    } 
} 

,註冊它像這樣:

public override void Configure(Container container) 
    { 
     container.Adapter = new MefIocAdapter(_mefContainer); 
    } 

由RegisterService(System.Type的,字符串)函數註冊服務之後,我越來越MEF的異常。它找不到出口:

ContractName ServiceStack.Auth.IAuthSession 
RequiredTypeIdentity ServiceStack.Auth.IAuthSession 

我誤解了一些東西嗎?

爲什麼Funq要求適配器容器解決內部ServiceStack的依賴性?

funq會使用MEF來實例化我的服務嗎? (如果沒有,有沒有像服務工廠?)

P.S.當我刪除container.Adapter分配它的作品(但我的MEF依賴項爲空)。

回答

2

當你註冊一個容器適配器時,你告訴ServiceStack到用適配器解決所有依賴關係,它只搜索ServiceStack的IOC,如果你的適配器中沒有找到依賴關係。

這裏的問題是,IAuthSession是一個可選屬性依賴項,如果依賴項不存在,那麼適配器應該返回null,ServiceStack可以檢查Funq中的依賴項。

在適配器的時候已經得到了錯誤的方式輪,其中Resolve<T>(用於解析構造函數依賴)返回默認值,當它不存在時,它應該返回默認值TryResolve<T>拋出異常。所以我會更改您的適配器實施:

public T TryResolve<T>() 
{ 
    return _container.GetExportedValueOrDefault<T>(); 
} 

public T Resolve<T>() 
{ 
    return _container.GetExportedValue<T>(); 
} 
+0

謝謝!多麼愚蠢的錯誤...我必須將funqContainer.CheckAdapterFirst設置爲true才能讓我的服務由MEF實例化,因爲服務也在funq容器中註冊,並且我的MefAdapter尚未被調用。 – smokeing