1

I would like to ask, is it possible to import some object by ExportMetadata value ? For example, string. Or If I declared some Export objects by name and type can I import all of them by just only type ?

1 Answer 1

3

You would need to defer the creation of the part through either Lazy or ExportFactory. E.g, given my sample type:

[Export(typeof(ILogger)), ExportMetadata("Name", "Console")]
public class ConsoleLogger : ILogger
{

}

I would need a metadata interface:

public interface INamedMetadata
{
  string Name { get; }
}

Then I could import many instances as:

[ImportMany(typeof(ILogger))]
IEnumerable<Lazy<ILogger, INamedMetadata>> Loggers { get; set; }

And make a selection:

public ILogger GetLogger(string name)
{
  return Loggers
    .Where(l => l.Metadata.Name.Equals(name))
    .Select(l => l.Value)
    .FirstOrDefault();
}
1
  • To add to this, the main benefit of this is that within the list of possible ILoggers, only the selected ILogger is instantiated at any one time. The others are available for use, but instances won't be created until l.Value is called.
    – Apache
    Jul 15, 2016 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.