.net - 使用 MEF 注册实例

标签 .net mef

我必须将一个对象实例注册到容器中。我无法使用通用 ComposeExportedValue<T>因为我不知道编译时 T 是什么。

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

有什么想法吗?

最佳答案

这是一个非通用的 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);
}

关于.net - 使用 MEF 注册实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2843078/

相关文章:

.net - 在 .NET 4 中使用 Fluent NHibernate + SQLite 有问题吗?

.net - 在 IQueryable 的 Select 中调用 DTO 转换器

c# - 什么时候将 RegistrationBuilder 传递给 Catalog?

visual-studio-2010 - Visual Studio 2010 着色器、智能感知等。从哪儿开始!

c# - 如何使用 MEF 从 dll 文件中提取图片

c# - MEF 和序列化

c# - 有关如何在 Windows 窗体中创建复合控件的教程?

.net - "Good"发布配置中的 ASP.net 堆栈跟踪或如何获取有问题的代码

.NET - JSON 数据 - 反序列化 - 列表和字典

c# - 具有依赖注入(inject)的类单例行为