使用MEF注册实例

4

我需要将一个对象实例注册到容器中。由于在编译时无法确定T的类型,因此无法使用通用的ComposeExportedValue<T>

我需要的方法类似于这样:container.RegisterInstance(Type someType, object instance)

有什么想法吗?

1个回答

2
这是一个不使用泛型的ComposeExportedValue版本:
public static void ComposeExportedValue(this CompositionContainer container, string contractName, object exportedValue) {
    if (container == null)
        throw new ArgumentNullException("container");
    if (exportedValue == null)
        throw new ArgumentNullException("exportedValue");
    CompositionBatch batch = new CompositionBatch();
    var metadata = new Dictionary<string, object> {
        { "ExportTypeIdentity", AttributedModelServices.GetTypeIdentity(exportedValue.GetType()) }
    };
    batch.AddExport(new Export(contractName, metadata, () => exportedValue));
    container.Compose(batch);
}

public static void ComposeExportedValue(this CompositionContainer container, object exportedValue) {
    if (container == null)
        throw new ArgumentNullException("container");
    if (exportedValue == null)
        throw new ArgumentNullException("exportedValue");
    ComposeExportedValue(container, AttributedModelServices.GetContractName(exportedValue.GetType(), exportedValue);
}

你确定这个能用吗?除了容器->组合参数名称不匹配之外,代码仍然无法正常工作。 - yang
好的,我的错误。更正合约名称解决了问题。非常感谢! - yang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接