Search code examples
c#pluginsdependency-injectioninversion-of-controlmef

Lazy<T, TMetaData> -> Lazy<dynamic, TMetaData> without instantiating?


I use MEF and compose parts and get several IEnumerable<Lazy<IFoo, IMetaData>> (I have several imports). I like to merge all of the composed parts into one collection of type IEnumerable<Lazy<dynamic, IMetaData>>. Is that possible without invoking/instantiating the actual objects that implement IFoo or other interfaces?

I look to setup a large collection of composable parts but I do not like to instantiate them until they are actually requested. (Please see my related question: MEF, why are identical duplicates of one and the same exported plugin created?


Solution

  • You should be able to do that by using something like:

    from enumerable in enumerables
    from lazy in enumerable
    select new Lazy<dynamic, IMetaData>(() => lazy.Value, lazy.Metadata)
    

    Unfortunately I do not have MEF at hand so please let me know if you will have any compilation problems. Note that lazy.Value is passed in a delegate and so not evaluated until needed.