[Export("SQL", typeof(ILogger))] public class SqlLogger : ILogger { public void WriteLog(string message) { Console.WriteLine("SQL Logger => {0}", message); } }
其中Export的第一个参数是协议名称,第二个参数则是导出的类型。对应的导入代码如下:
[Import("SQL", typeof(ILogger))] public ILogger SqlLogger { get; set; }
[Export("Oracal")] public class OracalLogger : ILogger { public void WriteLog(string message) { Console.WriteLine("Oracal Logger => {0}", message); } }上述导出协议并未指定导出类型,因此就以所修饰类作为其导出类型,即OracalLogger。相应的导入代码为:
[Import("Oracal")] public OracalLogger OracalLogger { get; set; }
其中属性的类型是OracalLogger,而不是ILogger。如果类型为ILogger,导入就会失败。
[Export(typeof(ILogger))] public class TxtLogger : ILogger { public void WriteLog(string message) { Console.WriteLine("Text Logger => {0}", message); } }上述导出协议未指定导出协议名称,只指定了导出类型。则相应的导入代码为:
[Import(typeof(ILogger))] public ILogger TextLogger { get; set; }
[Export] public class XmlLogger : ILogger { public void WriteLog(string message) { Console.WriteLine("Xml Logger => {0}", message); } }上述代码的导出协议名为默认协议,类型则与所修改的类相同,即XmlLogger,与之匹配的导入代码应该如下所示:
[Import] public XmlLogger XmlLogger { get; set; }