tags:

views:

21

answers:

3

Hi,

I would like to manually create exports for composition, but the Export constructor only accepts a dictionary for metadata, while I should directly create it from the metadata object (IMyMetadata). Isn't there a way to create the dictionary from the object? Something like this:

IDictionary<string, object> metadata = AttributedModelServices.GetMetadataDictionary(metadata)

where metadata is an IMyMetadata object.

Essentially, my need is that of using an imported IEnumerable> to create new compositions, sort of "forwarding" values to another CompositionBatch.

Thank you

A: 

You can import IEnumerable<IContract, IDictionary<string, object>> to get the raw metadata dictionary. It sounds like this would work for you.

Daniel Plaisted
Sorry, could you provide a short example, please?
fra
+1  A: 

Isn't there a way to create the dictionary from the object?

Sure, like this:

  public static IDictionary<string, object> GetPropertiesDictionary<T>(object o)
  {
     var dictionary = new Dictionary<string, object>();
     foreach (var property in typeof(T).GetProperties())
     {
        dictionary[property.Name] = property.GetValue(o,null);
     }
     return dictionary;
  }

Essentially, my need is that of using an imported IEnumerable to create new compositions, sort of "forwarding" values to another CompositionBatch

It sounds like you're trying to implement sort of a "ExportMany" feature, which does not (yet?) exist in MEF. (It does exist in some other IOC containers, like lightweight adapters in AutoFac). You may be able to do without such a feature.

I'm going to assume you have exports of some type (IStuff) available, but you need to wrap them in adapters so that you can import them as something else (IAdaptedStuff). Maybe you could stick to the normal attributed programming model and do something like this:

[Export(typeof(IAdaptedStuffUser))]
public class AdaptedStuffUser : IAdaptedStuffUser
{
   [Import] // instead of [ImportMany(typeof(IAdaptedStuff)))]
   public IAdaptedStuffProvider AdaptedStuffProvider { private get; set; }

   public void DoSomething()
   {
      foreach (var adaptedStuff in AdaptedStuffProvider.GetAdaptedStuff())
      {
         ...
      }
   }
}

[Export(typeof(IAdaptedStuffProvider))]
public AdaptedStuffProvider : IAdaptedStuffProvider
{
   [ImportMany]
   public IEnumerable<IStuff> StuffToAdapt { get; set; }

   public IEnumerable<IAdaptedStuff> GetAdaptedStuff()
   {
      return StuffToAdapt.Select(x => new Adapter(x));
   }
}
Wim Coenen
Thank you. I already had the solution with reflection, I was searching for a sort of utility method within MEF. Anyway, the 'AdaptedStuffProvider" is a good hint; hence, this is an acceptable answer.
fra
A: 

For example:

[ImportMany]    
IEnumerable<IContract, IDictionary<string, object>> MyContracts { get; set; }
hammett
Now I understand, thank you. But I'd prefer having strongly typed interfaces.
fra