Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MEF usage with static classes

Tags:

c#

.net

c#-4.0

mef

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)

like image 903
noaRAVE Avatar asked Jan 09 '12 09:01

noaRAVE


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

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.

like image 120
Wim Coenen Avatar answered Oct 12 '22 11:10

Wim Coenen