2015-09-28 39 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