I am trying to dynamically (using reflection) add types to a MEF catalog and also define the export contract at runtime. The issue is MEF will simply use the fully qualified name of the type as the contract, and I need to specify the export contract as a specific interface type.
Here is the code I use to get the types I need to add to the MEF catalog:
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 = ty开发者_如何转开发peof(EFRepository<>).MakeGenericType(entityType);
ComponentServices.RegisterComponent(repositoryType);
}
}
ComponentServices.RegisterComponent is defined below, it gets an AggregateCatalog (from where isn't relevant) and then adds TypeCatalogs to the aggregate catalog:
public static void RegisterComponent(Type componentType)
{
var catalog = RetrieveCatalog();
catalog.Catalogs.Add(new TypeCatalog(componentType));
}
I need to be able to specify the contract of the added types as an interface, this would normally be done with Export attributes that look like this:
[Export(typeof(IRepository<Customer>))]
The question is how do I add this export contract dynamically, so that the export is equivalent to what's shown above and not the default "EFRepository" contract that MEF infers from the type itself.
If you can use the CodePlex preview version of MEF, I'd recommend using the new RegistrationBuilder to do this. Here's a blog post describing it: MEF's Convention Model
If you can't use the preview version, you can use the methods in ReflectionModelServices to create your own part definitions, and create a catalog implementation that uses them.
加载中,请稍侯......
精彩评论