2

I'm fighting with MEF and I stopped at some problem - in my App I have singleton class:

class Config: IConfig {
}

which stores App config data - loaded for example from XML files, DB etc

Now I have some plugins which must have access to the Config - so I wonder what is the best solution to pass the Config to plugin?

My solution for now is:

[ImportMany(typeof (IFieldPlugin))]
public IEnumerable<Lazy<IFieldPlugin, IFieldPluginData>> fieldPlugins;


foreach (var plugin in PluginsStorage.Instance.fieldPlugins)
{
    if (plugin.Metadata.Name.Equals(field.Plugin))
    {
        if(!plugin.IsValueCreated) {
            plugin.Value.Config = Config.Instance;
        }
        result = plugin.Value.DoStep(this,url);
    }
}

Any better solution?

ekapek
  • 209
  • 1
  • 6
  • 20

4 Answers4

2

What about creating an instance of the Config class early in the lifecycle of the application and export from there?

Can then import in constructor or as a property.

2

The MEF way to do it, is to not access the configuration manager through the instance field but rather to let MEF create the shared instance by by adding the PartCreationAttribute like so

[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IConfig))]
class Config: IConfig {}

and adding the appropriate import on your plugins. As long as the config type is in the catalog when you are doing composition it should just be set on your plugins.

Yaur
  • 7,333
  • 1
  • 25
  • 36
2

Normally you'd do something like this; In the plugin assembly:

[Export(typeof(IPlugin))]
public class MyPlugin : IPlugin
{
    private readonly IConfig config;

    [ImportingConstructor]
    public MyPlugin(IConfig config)
    {
        if (config == null)
            throw new ArgumentNullException("config");
        this.config = config;
    }
}

In one of the core application assemblies:

[Export(typeof(IConfig))]
public class Config : IConfig
{
   ...
}
Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
1

What I usually do is have a common assembly for all plugins where i put also contracts, in this case for ex. IConfigurationManager.

Then on the bootstrapper, i create a CompositionBatch where i put there the configuration manager and since every plugins knows about IConfigurationManager than I can easily import it whenever i need it.