简体   繁体   中英

C# MEF usage with static classes

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)

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM