Querying the CompositionContainer
CompositionContainer 의 Exported 구성 요소를 취득하기 위해서는 컨테이너에 하나의 구성 요소만이 존재해야 합니다. 쿼리(Query) 를 통해 이러한 객체들이 여러 개 존재할 경우 MEF 는 예외를 발생하게 됩니다.
바로 아래와 같은 경우이죠.
l 하나의 인스턴스를 요청할 때, 인스턴스를 찾지 못했을 경우
l 하나의 인스턴스를 요청할 때, 인스턴스가 여러 개일 경우
GetExportedObject
일반적으로 ExportAttribute 에 인자가 전달되지 않은 경우는 클래스의 타입이 키 값이 되어, 아래와 같이 구성 요소를 취득할 수 있습니다.
class Program { static void Main(string[] args) { var container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly())); var export = container.GetExportedObject<Export1>(); export.Say(); Console.ReadKey(); } } [Export] class Export1 { public void Say() { Console.WriteLine("Export1 Say.."); } } |
만약, ExportAttribute 에 Contract Name 이 선언이 될 경우는 클래스의 타입 정보와 Contract Name 이 일치해야 구성요소를 취득할 수 있습니다.
class Program { static void Main(string[] args) { var container = new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly())); var export = container.GetExportedObject<Export2>("export2"); export.Say(); Console.ReadKey(); } } [Export("export2")] public class Export2 { public void Say() { Console.WriteLine("Export2 Say.."); } } |
GetExport
만약 여러 개의 구성 요소의 인스턴스가 필요하다면 GetExport 메서드를 통해 Export 의 구성 정보를 가져오면 됩니다.
var exports = container.GetExport<Export1>(); exports.GetExportedObject().Say(); |
필요하다면 ExportAttribute 의 Contract Name 으로 질의(Query) 할 수 있습니다.
var exports = container.GetExport<Export2>("export2"); exports.GetExportedObject().Say(); |
아쉽게도 MEF Preview 4 까지 지원하던 C# 3.0 의 Expression 을 통해 질의하는 방법은 MEF Preview 5 이후 없어진 것이 아쉽네요.
GetExportedObjectOrDefault
일반적으로 MEF 에서는 질의(Query) 결과가 없을 경우 예외를 발생하게 되는데, GetExportedObjectOrDefault 메서드를 통해 결과가 없을 경우 Null 값으로 대체할 수 있습니다.
var obj = container.GetExportedObjectOrDefault<Export1>("A"); if( obj != null ) obj.Say(); |