使用运行时定义的合约动态注册MEF导出

时间:2011-06-20 19:10:17

标签: c# .net mef

我正在尝试动态(使用反射)向MEF目录添加类型,并在运行时定义导出协定。问题是MEF只是使用类型的完全限定名称作为合同,我需要将导出合同指定为特定的接口类型。

以下是我用来获取我需要添加到MEF目录的类型的代码:

private void RegisterSupportedRepositories(Func<ObjectContext> contextProvider)
    {
        var context = contextProvider();
        var properties = context.GetType().GetProperties();
        var entitySets = properties.Where(property => property.PropertyType.Name == typeof(ObjectSet<>).Name);

        foreach (var entitySet in entitySets)
        {
            var entityType = entitySet.PropertyType.GetGenericArguments()[0];
            var repositoryType = typeof(EFRepository<>).MakeGenericType(entityType);
            ComponentServices.RegisterComponent(repositoryType);                
        }
    }
  

ComponentServices.RegisterComponent定义如下,它获取AggregateCatalog(从哪里不相关),然后将TypeCatalogs添加到聚合目录中:

public static void RegisterComponent(Type componentType)
    {
        var catalog = RetrieveCatalog();

        catalog.Catalogs.Add(new TypeCatalog(componentType));
    }

我需要能够将添加类型的合同指定为接口,这通常可以使用如下所示的Export属性来完成:

[Export(typeof(IRepository<Customer>))]

问题是如何动态添加此导出合约,以便导出等同于上面显示的内容,而不是MEF从类型本身推断的默认“EFRepository”合同。

1 个答案:

答案 0 :(得分:1)

如果您可以使用MEF的CodePlex预览版,我建议您使用新的RegistrationBuilder来执行此操作。这是一篇描述它的博客文章:MEF's Convention Model

如果您无法使用预览版本,则可以使用ReflectionModelServices中的方法创建自己的零件定义,并创建使用它们的目录实现。

相关问题