// ----------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; namespace System.ComponentModel.Composition { internal static class CompositionContainerExtensions { public static bool IsPresent(this ExportProvider container) { try { container.GetExportedValue(); return true; } catch (ImportCardinalityMismatchException) { return false; } } public static bool IsPresent(this ExportProvider container, string contractName) { try { container.GetExportedValue(contractName); return true; } catch (ImportCardinalityMismatchException) { return false; } } public static void AddAndComposeExportedValue(this CompositionContainer container, T exportedValue) { var batch = new CompositionBatch(); batch.AddExportedValue(exportedValue); container.Compose(batch); } public static void AddAndComposeExportedValue(this CompositionContainer container, string contractName, T exportedValue) { var batch = new CompositionBatch(); batch.AddExportedValue(contractName, exportedValue); container.Compose(batch); } public static void AddParts(this CompositionBatch batch, params object[] parts) { foreach (object instance in parts) { ComposablePart part = instance as ComposablePart; if (part != null) { batch.AddPart(part); } else { batch.AddPart((object)instance); } } } public static ComposablePart AddExportedValue(this CompositionBatch batch, string contractName, Type contractType, object exportedValue) { string typeIdentity = AttributedModelServices.GetTypeIdentity(contractType); IDictionary metadata = null; if (typeIdentity != null) { metadata = new Dictionary(); metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity); } return batch.AddExport(new Export(contractName, metadata, () => exportedValue)); } } }