Search code examples
c#mef.net-assembly

How to get the assembly information of an imported MEF function?


Is it possible get the assembly information from an imported MEF function? I need to know the assembly version and name of the Plugin control that contains the function. Tried the following, but it just returns the System.ComponentModel.Composition version.

foreach (Lazy<Func<int>, IMetadata> func in PluginFuncs)
{
    // get assembly information of the Plugin control for the imported function 
    string version = func.GetType().Assembly.GetName().Version.ToString();
    Console.WriteLine(version);
}

Another alternative would be to use hardcoded values in the metadata, but I thought this would not be maintainable. It would be easy to forget to change those values when the version changed.


Solution

  • You need to check the type from within func.Value, not the Lazy<T,TMeta> wrapping it. Try:

    Func<int> lambdaFunc = func.Value;
    Delegate del = lambdaFunc;
    string version = del.Method.ReflectedType.Assembly.GetName().Version.ToString();
    

    However, realize that this will evaluate the Lazy<T> at this point - but this is required, because the object where you are trying to get the type hasn't be constructed until you evaluate that.