MEF metadata dictionary from object
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 Compositi开发者_开发技巧onBatch.
Thank you
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));
}
}
You can import IEnumerable<IContract, IDictionary<string, object>>
to get the raw metadata dictionary. It sounds like this would work for you.
For example:
[ImportMany]
IEnumerable<IContract, IDictionary<string, object>> MyContracts { get; set; }
精彩评论