开发者

Import object by ExportMetadata attribute in MEF

开发者 https://www.devze.com 2023-02-23 03:27 出处:网络
I would like to ask, is it possible to impor开发者_如何学Ct some object by ExportMetadata value ? For example, string.

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();
}
0

精彩评论

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