开发者

Automatlcally distinguish the caller in MEF

Using MEF, from inside the exporter, is it possible to find out who is importer using metadata ?

for example is this possible:

[Export("Config")]
S开发者_如何学Pythontring Config()
{
   if (importer.metedata["name"] == "Circle")
   return "R=10";
}

This way importer doesn't need to pass something (his name, here) to tell the exporter who is he.


No, you can't do that. It makes more sense to do this:

[Export("Config")]
string GetConfigurationValue(string name)
{
   if (name == "Circle")
   {
       return "R=10";
   }
   throw new ArgumentException(
       string.Format("Unknown configuration value '{0}'", name));
}

And the class which imports this method could look like this:

[Export(typeof(IDrawer))]
public class CircleDrawer : IDrawer
{
    [Import("Config")]
    public Func<string,string> ConfigGetter { get; set; }

    public void Draw()
    {
        string configuration = this.ConfigGetter("Circle");
        ...
    }
}

Note that directly importing and exporting methods (as System.Action or System.Func) is the quick and dirty way.

It is better to declare a IConfigurationProvider interface instead and export that at the class level. This has two advantages:

  • the interface documentation is where you can document the contract that the importer and exporter have to agree on.
  • it eliminates the needs for those pesky strings in the import/export attributes by replacing them by typeof(IConfigurationProvider).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜