Xaisoft
Xaisoft

Reputation: 46591

How to setup the proper MEF configuration?

I have a class library with one class called IConfiguration which is an interface with just one property.

I have a class library called TexasConfiguration which implements IConfiguration and another class library called FloridaConfiguration which implements IConfiguration.

I have decorated TexasConfiguration and FloridaConfiguration with [Export(typeof(IConfiguration)]

I have another class which is sealed class called ConfigurationSystem and it contains a private constructor defined as private ConfigurationSystem() {}

There are few issues I have. Generally speaking, where should I put the MEF stuff to set it up. Currently, I have put a static method in ConfigurationSystem along with the following declaration:

[Import(typeof(IConfiguration)]
IConfiguration configuration {get; set;}

In the above, it tells me that configuration is unused. Is this normal in this case.

I also created a static method in ConfigurationSystem,but if I make it static, I can't pass this to it, I have to pass typeof(ConfigurationSystem) to it:

public static void SetupConfiguration()
    {
        using (DirectoryCatalog catalog = new DirectoryCatalog(@"c:\\developement\source\configuration"))
        {
            CompositionContainer container = new CompositionContainer(catalog);
            container.ComposeParts(typeof(ConfigurationSystem));
        }
    }

I want to be able to do something like:

ConfigurationSystem.SetupConfiguration();

but I can't do this unless the method is declared static. In a nutshell, when the application is started, it calls a static method Initialize where I want to call my SetupConfiguration and assign the appropriate configuration object to IConfiguration.

Upvotes: 3

Views: 532

Answers (1)

Adi Lester
Adi Lester

Reputation: 25201

MEF is designed to work with object instances, not with static classes. The call to container.ComposeParts(typeof(ConfigurationSystem)) will do absolutely nothing, since what you're basically asking here is for MEF to compose the parts for the Type object you passed to it, which is obviously not what you wanted.

There is a simple solution though that won't cause you to change your application's architecture too much. You could make your ConfigurationSystem class a singleton, and then you'll be able to call container.ComposeParts(this) and get your parts.

Upvotes: 1

Related Questions