C# MEF usage with static classes

2020-07-04 07:16发布

问题:

I have a static class in my solution which is used to work with various assemblies. I want to link them through MEF, so I made a field in a class.

[Import(typeof(A))]
    static private A _a1;

Then I have a method to which I pass assembly name as an argument:

    public static A LoadPackage(string filePath)
    {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(filePath));
            var _container = new CompositionContainer(catalog);
            ???
    }

So is there a way now to import type from assembly specified by filepath?

I can't do:

_container.ComposeParts(this);

since class is `static and neither can I do this

_container.ComposeParts(_a1);

(which might be completely wrong to begin with) since A doesn't have any constructors(so _a1 is null)

回答1:

MEF is designed to create and initialize objects for you. It doesn't deal with state in static classes.

I suggest that you make the class and its fields non-static, and mark it with [PartCreationPolicy(CreationPolicy.Shared)] if you want to enforce singleton behavior.

See also this other question on MEF and the singleton pattern.



回答2:

Well it turns out that method I was looking for is GetExportedValue (yeah, I overlooked basic functionality):

static private A _a1;

public static A LoadPackage(string filePath)
{
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(filePath));
        var _container = new CompositionContainer(catalog);
        _a1 = _container.GetExportedValue<A>();
}

And I got my field filled (just in case, I already moved it to another class, and it looks neat and clean now)



标签: c# .net c#-4.0 mef