static methods and MEF

Nov 30, 2009 at 9:19 AM
Edited Nov 30, 2009 at 9:20 AM

Hello,

I have a question regarding static methods and MEF.

I have a class:

[Export("MEFTest.StaticMethod")]
public class TestClass
{
    public static string StaticMethod(string tekst)
    {
        return tekst;
    }
}

in a separate assembly.

Is it possible to call method StaticMethod using MEF? TestClass doesn't implement any interface.

I am sorry of this is a re-post, but I searched the site and could not find anything that is useful.

Regards,

Mita Cokic

Nov 30, 2009 at 9:44 AM

Yes it is. To do so you put an Export attribute on the method rather than the class. For example instead of your snippet above, do the following:

public static class TestClass
{
    [Export("MEFTest.StaticMethod")]  
    public static string StaticMethod(string test)
    {
        return test;
    }
}

Then on the import side, you import into a delegate which matches the signature for example you would import the above into a member of type Func<string,string>. MEF also supports custom delegates, you could create your own delegate that matches the signature and it will also work.

Regards

Glenn

Nov 30, 2009 at 10:10 AM

Thank you Glenn for your quick response.

It works!

Regards,

Mita Cokic