I would like to ask, is it possible to impor开发者_如何学Ct 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 ?
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();
}
精彩评论