Florim Maxhuni
Florim Maxhuni

Reputation: 1421

MEF Import Scenario

Hi I have some problems in import scenarios example:

 [Export(typeof(IICon))]
public class WriteInputData : IICon
{
    [Import(typeof(IIOWriter))]
    public IIOWriter IOWriter { get; set; }

    public object Input { get; set; }

    public void Process()
    {
        IOWriter.Write(Input);
    }
}

Then i hawe two classes that implement interface IIOWriter like :

[Export(typeof(IIOWriter))]
public class FileWriter : IIOWriter
{
    public string FilePath { get; set; }

    public void Write(object data)
    {
        if (string.IsNullOrEmpty(FilePath))
            FilePath = @"c:\test.txt";
        var fl = new StreamWriter(FilePath, true);
        fl.Write((string)data);
        fl.Flush();
        fl.Close();
    }

    public string Name
    {
        get { return "FileWriter"; }
    }
}
[Export(typeof(IIOWriter))]
public class ConsoleWrite : IIOWriter
{
    public void Write(object data)
    {
        Console.WriteLine((string)data);
    }

    public string Name
    {
        get { return "ConsoleWrite"; }
    }
}

How can i let that to user so he can change that in runtime, so example whene he type select in ListBox FileWriter than the IIOWriter in WriteInputData will be injected FileWriter end so one.. Sorry for my bad english.

Upvotes: 1

Views: 214

Answers (1)

Matthew Abbott
Matthew Abbott

Reputation: 61589

You probably need to supply some metadata to the export, such like:

[Export(typeof(IIOWriter)),
 ExportMetadata("Name", "ConsoleWriter")]
public class ConsoleWriter : IIOWriter
{

}

The reason you need to do this, is that you need to know ahead of time what the user selection will match to. Because of this, you may want to refactor your design to remove the dependency on the IOWriter property:

[Export(typeof(IICon))]
public class WriteInputData : IICon
{
  public object Input { get; set; }

  public void Process(IIOWriter writer)
  {

  }
}

If you define your Process method to take in an instance, we can resolve it using the CompositionContainer. Firstly, define a metadata interface that matches your ExportMetadata value:

public interface INamedMetadata
{
  string Name { get; }
}

And then, we can resolve the instance:

public IIOWriter GetWriter(string name)
{
  return container
    .GetExports<IIOWriter, INamedMetadata>()
    .Where(e => e.Metadata.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
    .Select(e => e.Value)
    .FirstOrDefault();
}

Hope that points you in the right direction....

Upvotes: 2

Related Questions