Beispiel #1
0
        public void Configure(ApplicationConfigurationBase applicationConfiguration)
        {
            if (IsConfigured)
            {
                return;
            }

            // Compose app container
            var batch = new CompositionBatch();

            foreach (var entry in _Entries)
            {
                var entryType    = entry.GetType();
                var contractName = AttributedModelServices.GetContractName(entryType);
                var typeIdentity = AttributedModelServices.GetTypeIdentity(entryType);
                var metadata     = new Dictionary <string, object> {
                    { "ExportTypeIdentity", typeIdentity }
                };
                batch.AddExport(new Export(contractName, metadata, () => entry));
            }

            applicationConfiguration.CompositionContainer.Compose(batch);

            IsConfigured = true;
        }
Beispiel #2
0
        /// <summary>
        /// Adds a provider delete that returns an exported value.
        /// </summary>
        /// <typeparam name="T">Type of the exported value.</typeparam>
        /// <typeparam name="S">Type of the state object for the provider function.</typeparam>
        /// <param name="container">The composition container where the value(s) should be exported.</param>
        /// <param name="contractName">The nae of the contract.</param>
        /// <param name="exportedValueProvider">The function that returns the exported value.</param>
        /// <param name="providerStateFactory">
        /// The function that returns the state object for <paramref name="exportedValueProvider" />.
        /// </param>
        /// <returns>The underlying created composable part object.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="container" />, <paramref name="exportedValueProvider" /> and/or
        /// <paramref name="providerStateFactory" /> are <see langword="null" /> references.
        /// </exception>
        public static ComposablePart AddExportedValueProvider <T, S>(this CompositionContainer container, IEnumerable <char> contractName, Func <CompositionContainer, string, S, T> exportedValueProvider, Func <CompositionContainer, string, S> providerStateFactory)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            if (exportedValueProvider == null)
            {
                throw new ArgumentNullException("exportedValueProvider");
            }

            if (providerStateFactory == null)
            {
                throw new ArgumentNullException("providerStateFactory");
            }

            var cn = contractName.AsString();

            var batch  = new CompositionBatch();
            var result = batch.AddExport(new Export(cn, new Dictionary <string, object>
            {
                { "ExportTypeIdentity", AttributedModelServices.GetTypeIdentity(typeof(T)) },
            }, () =>
            {
                return(exportedValueProvider(container,
                                             cn,
                                             providerStateFactory(container, cn)));
            }));

            container.Compose(batch);
            return(result);
        }
        public void MefCtor_CheckExports()
        {
            var batch = new CompositionBatch();

            var stores = new[]
            {
                new Mock <IIssuesStore>(),
                new Mock <IIssuesStore>(),
                new Mock <IIssuesStore>()
            };

            foreach (var issuesStore in stores)
            {
                issuesStore.SetupAdd(x => x.IssuesChanged += null);
                batch.AddExport(MefTestHelpers.CreateExport <IIssuesStore>(issuesStore.Object));
            }

            var locationStoreImport = new SingleObjectImporter <IIssueLocationStore>();

            batch.AddPart(locationStoreImport);

            using var catalog   = new TypeCatalog(typeof(AggregatingIssueLocationStoreAdapter));
            using var container = new CompositionContainer(catalog);
            container.Compose(batch);

            locationStoreImport.Import.Should().NotBeNull();

            // Verify that the stores are used
            foreach (var issuesStore in stores)
            {
                issuesStore.VerifyAdd(x => x.IssuesChanged += It.IsAny <EventHandler <IssuesStore.IssuesChangedEventArgs> >(), Times.Once);
            }
        }
Beispiel #4
0
        protected virtual void OnInitialize()
        {
            var catalog = new AggregateCatalog();

            foreach (var item in this.GetAssemblies())
            {
                catalog.Catalogs.Add(new AssemblyCatalog(item));
            }

            this.container = new CompositionContainer(catalog, true);

            var batch = new CompositionBatch();

            batch.AddPart(this.settings);
            foreach (var item in this.GetParts())
            {
                var contractName = AttributedModelServices.GetContractName(item.Item1);
                var typeIdentity = AttributedModelServices.GetTypeIdentity(item.Item1);
                batch.AddExport(new Export(contractName, new Dictionary <string, object>
                {
                    {
                        "ExportTypeIdentity",
                        typeIdentity
                    }
                }, () => item.Item2));
            }

            this.container.Compose(batch);
        }
        public void SatisfyImportsOnce(ComposablePart part)
        {
            if (this.DoNothingOnSatisfyImportsOnce)
            {
                return;
            }

            CompositionBatch batch = new CompositionBatch();

            // We only want to include the standard exports and parts to compose in the first composition
            if (!this.alreadyComposed)
            {
                foreach (object instance in this.PartsToCompose)
                {
                    batch.AddPart(instance);
                }

                foreach (Export export in this.ExportsToCompose)
                {
                    batch.AddExport(export);
                }
            }

            if (part != null)
            {
                batch.AddPart(part);
            }

            this.container.Compose(batch);
            this.alreadyComposed = true;
        }
        public void AddExport_NullAsExportArgument_ShouldThrowArgumentNull()
        {
            CompositionBatch batch = new CompositionBatch();

            Assert.Throws <ArgumentNullException>("export", () =>
            {
                batch.AddExport((Export)null);
            });
        }
Beispiel #7
0
        public void MefCtor_CheckExports()
        {
            var batch = new CompositionBatch();

            batch.AddExport(MefTestHelpers.CreateExport <IIssueLocationStore>(Mock.Of <IIssueLocationStore>()));
            batch.AddExport(MefTestHelpers.CreateExport <IIssueLocationStore>(Mock.Of <IIssueLocationStore>()));
            batch.AddExport(MefTestHelpers.CreateExport <IIssueLocationStore>(Mock.Of <IIssueLocationStore>()));

            var issueLocationStoreAggregatorImporter = new SingleObjectImporter <IIssueLocationStoreAggregator>();

            batch.AddPart(issueLocationStoreAggregatorImporter);

            using var catalog   = new TypeCatalog(typeof(IssueLocationStoreAggregator));
            using var container = new CompositionContainer(catalog);
            container.Compose(batch);

            issueLocationStoreAggregatorImporter.Import.Should().NotBeNull();
        }
Beispiel #8
0
        public static void RegisterFunc <T>(this CompositionContainer container, Func <T> functor)
        {
            var batch        = new CompositionBatch();
            var contractName = AttributedModelServices.GetContractName(typeof(T));
            var typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T));
            IDictionary <string, object> metadata = new Dictionary <string, object>();

            metadata.Add("ExportTypeIdentity", typeIdentity);
            batch.AddExport(new Export(contractName, metadata, () => functor()));
            container.Compose(batch);
        }
Beispiel #9
0
        /// <summary>
        ///  Creates a part from the specified object under the specified contract name and composes it in the specified
        ///  composition container.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="contractName"></param>
        /// <param name="exportedValue"></param>
        public static void ComposeExportedValue(this CompositionContainer container, string contractName, object exportedValue)
        {
            Contract.Requires <ArgumentNullException>(container != null);
            Contract.Requires <ArgumentNullException>(contractName != null);
            Contract.Requires <ArgumentNullException>(exportedValue != null);

            var b = new CompositionBatch();
            var m = new Dictionary <string, object>();

            b.AddExport(new Export(contractName, m, () => exportedValue));
            container.Compose(b);
        }
        public static ComposablePart AddExportedValue <T>(this CompositionBatch batch, string contractName, T exportedValue)
        {
            Requires.NotNull(batch, nameof(batch));

            string typeIdentity = AttributedModelServices.GetTypeIdentity(typeof(T));

            IDictionary <string, object?> metadata = new Dictionary <string, object?>();

            metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity);

            return(batch.AddExport(new Export(contractName, metadata, () => exportedValue)));
        }
Beispiel #11
0
        protected override void Configure()
        {
            // Add New ViewLocator Rule
            ViewLocator.NameTransformer.AddRule(
                @"(?<nsbefore>([A-Za-z_]\w*\.)*)?(?<nsvm>ViewModels\.)(?<nsafter>([A-Za-z_]\w*\.)*)(?<basename>[A-Za-z_]\w*)(?<suffix>ViewModel$)",
                @"${nsbefore}Views.${nsafter}${basename}View",
                @"(([A-Za-z_]\w*\.)*)?ViewModels\.([A-Za-z_]\w*\.)*[A-Za-z_]\w*ViewModel$"
                );

            container = new CompositionContainer(
                new AggregateCatalog(
                    new AssemblyCatalog(typeof(IShellViewModel).Assembly),
                    AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>().FirstOrDefault())
                );

            var batch = new CompositionBatch();

            batch.AddExport <IWindowManager>(() => new WindowManager());
            batch.AddExport <IEventAggregator>(() => new EventAggregator());
            container.Compose(batch);
        }
        /// <summary>
        ///  Creates a part from the specified object under the specified contract name and composes it in the specified
        ///  composition container.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="contractName"></param>
        /// <param name="exportedValue"></param>
        public static void ComposeExportedValue(this CompositionContainer container, string contractName, object exportedValue)
        {
            Debug.Assert(container != null);
            Debug.Assert(contractName != null);
            Debug.Assert(exportedValue != null);

            var b = new CompositionBatch();
            var m = new Dictionary <string, object>();

            b.AddExport(new Export(contractName, m, () => exportedValue));
            container.Compose(b);
        }
        public void AddExport_ReturnedComposablePart_IsInAddedPartsCollection()
        {
            CompositionBatch batch = new CompositionBatch();

            var export = ExportFactory.Create("Contract", "Value");
            var part   = batch.AddExport(export);

            Assert.Equal(1, batch.PartsToAdd.Count);

            Assert.Equal("Value", this.GetSingleExport(batch.PartsToAdd[0], "Contract").Value);
            Assert.Contains(part, batch.PartsToAdd);
        }
        public void MefCtor_CheckExports()
        {
            CompositionBatch batch = new CompositionBatch();

            // Set up the exports required by the test subject
            var fileRenamesEventSourceExport = MefTestHelpers.CreateExport <IFileRenamesEventSource>(Mock.Of <IFileRenamesEventSource>());

            batch.AddExport(fileRenamesEventSourceExport);

            var tableManagerExport = MefTestHelpers.CreateExport <ITableManagerProvider>(mockTableManagerProvider.Object);

            batch.AddExport(tableManagerExport);

            var selectionServiceExport = MefTestHelpers.CreateExport <IIssueSelectionService>(Mock.Of <IIssueSelectionService>());

            batch.AddExport(selectionServiceExport);

            // Set up importers for each of the interfaces exported by the test subject
            var errorDataSourceImporter    = new SingleObjectImporter <ISonarErrorListDataSource>();
            var issueLocationStoreImporter = new SingleObjectImporter <IIssueLocationStore>();

            batch.AddPart(errorDataSourceImporter);
            batch.AddPart(issueLocationStoreImporter);

            // Specify the source types that can be used to satify any import requests
            TypeCatalog catalog = new TypeCatalog(typeof(SonarErrorListDataSource));

            using (CompositionContainer container = new CompositionContainer(catalog))
            {
                container.Compose(batch);

                // Both imports should be satisfied...
                errorDataSourceImporter.Import.Should().NotBeNull();
                issueLocationStoreImporter.Import.Should().NotBeNull();

                // ... and the the export should be a singleton, so the both importers should
                // get the same instance
                errorDataSourceImporter.Import.Should().BeSameAs(issueLocationStoreImporter.Import);
            }
        }
Beispiel #15
0
        public static void ComposeExportedValue(CompositionContainer container, object exportedValue)
        {
            CompositionBatch batch = new CompositionBatch();

            var metadata = new Dictionary <string, object> {
                { "ExportTypeIdentity", "TransformationCore.ITransformation" },
                { "Name", "test" }
            };

            batch.AddExport(new Export("TransformationCore.ITransformation", metadata, () => exportedValue));

            container.Compose(batch);
        }
        public void AddExport_ExportWithNullExportedValueAsExportArgument_CanBeExported()
        {
            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", (object)null);

            batch.AddExport(export);
            Assert.Equal(1, batch.PartsToAdd.Count);

            var result = this.GetSingleExport(batch.PartsToAdd[0], "Contract");

            Assert.NotNull(result);
            Assert.Null(result.Value);
        }
Beispiel #17
0
        public static ComposablePart AddExportedValue(this CompositionBatch batch, string contractName, Type contractType, object exportedValue)
        {
            string typeIdentity = AttributedModelServices.GetTypeIdentity(contractType);

            IDictionary <string, object> metadata = null;

            if (typeIdentity != null)
            {
                metadata = new Dictionary <string, object>();
                metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity);
            }

            return(batch.AddExport(new Export(contractName, metadata, () => exportedValue)));
        }
        public void AddExport_ReturnedComposablePart_NullAsDefinitionArgumentToSetImports_ShouldThrowArgumentNull()
        {
            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", "Value");

            var part = batch.AddExport(export);

            Assert.Equal(1, batch.PartsToAdd.Count);

            Assert.Throws <ArgumentNullException>("definition", () =>
            {
                part.SetImport((ImportDefinition)null, Enumerable.Empty <Export>());
            });
        }
        public void AddExport_ExportWithEmptyMetadata_IsExportedWithEmptyMetadata()
        {
            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", "Value", new Dictionary <string, object>());

            Assert.Equal(0, export.Metadata.Count);

            batch.AddExport(export);
            Assert.Equal(1, batch.PartsToAdd.Count);

            var result = this.GetSingleExport(batch.PartsToAdd[0], "Contract");

            Assert.Equal(0, result.Metadata.Count);
        }
        private static void TryCompose(object importer, TypeCatalog catalog, IEnumerable <Export> exports)
        {
            CompositionBatch batch = new CompositionBatch();

            batch.AddPart(importer);
            foreach (Export item in exports)
            {
                batch.AddExport(item);
            }
            using (CompositionContainer container = new CompositionContainer(catalog))
            {
                container.Compose(batch);
            }
        }
Beispiel #21
0
        public static ComposablePart AddExport <TKey>(this CompositionBatch batch, Func <object> func)
        {
            var typeString = typeof(TKey).ToString();

            return(batch.AddExport(
                       new Export(
                           new ExportDefinition(
                               typeString,
                               new Dictionary <string, object>()
            {
                { "ExportTypeIdentity", typeString }
            }),
                           func)));
        }
Beispiel #22
0
        public void AddExport_ReturnedComposablePart_NullAsDefinitionArgumentToGetExportedValue_ShouldThrowArgumentNull()
        {
            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", "Value");

            var part = batch.AddExport(export);

            Assert.AreEqual(1, batch.PartsToAdd.Count);

            ExceptionAssert.ThrowsArgument <ArgumentNullException>("definition", () =>
            {
                part.GetExportedValue((ExportDefinition)null);
            });
        }
Beispiel #23
0
        public static void ComposeExportedValue(this CompositionContainer container, Type contractType, object exportedValue)
        {
            Contract.Requires <ArgumentNullException>(container != null);
            Contract.Requires <ArgumentNullException>(contractType != null);
            Contract.Requires <ArgumentNullException>(exportedValue != null);

            var contractName = AttributedModelServices.GetTypeIdentity(contractType);
            var b            = new CompositionBatch();
            var m            = new Dictionary <string, object>();

            m[CompositionConstants.ExportTypeIdentityMetadataName] = contractName;
            b.AddExport(new Export(contractName, m, () => exportedValue));
            container.Compose(b);
        }
        public void AddExport_ReturnedComposablePart_ExportsArrayWithNullElementAsExportsArgumentToSetImports_ShouldThrowArgument()
        {
            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", "Value");

            var part       = batch.AddExport(export);
            var definition = ImportDefinitionFactory.Create();

            Assert.Equal(1, batch.PartsToAdd.Count);

            Assert.Throws <ArgumentException>("exports", () =>
            {
                part.SetImport(definition, new Export[] { null });
            });
        }
Beispiel #25
0
        public void AddExport_ReturnedComposablePart_SetImports_ShouldThrowArgument()
        {
            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", "Value");

            var part       = batch.AddExport(export);
            var definition = ImportDefinitionFactory.Create();

            Assert.AreEqual(1, batch.PartsToAdd.Count);

            ExceptionAssert.ThrowsArgument <ArgumentException>("definition", () =>
            {
                part.SetImport(definition, Enumerable.Empty <Export>());
            });
        }
Beispiel #26
0
        public void Register(Func <object> factory, Type serviceType, string contract = null)
        {
            var batch = new CompositionBatch();

            if (contract == null)
            {
                contract = AttributedModelServices.GetContractName(serviceType);
            }
            var typeIdentity = AttributedModelServices.GetTypeIdentity(serviceType);
            var metadata     = new Dictionary <string, object>
            {
                ["ExportTypeIdentity"] = typeIdentity,
            };

            batch.AddExport(new Export(contract, metadata, factory));
            _container.Compose(batch);
        }
        private CompositionBatch CreateBatch(IEnumerable <Tuple <Type, object> > parts)
        {
            var batch = new CompositionBatch();

            foreach (var item in parts)
            {
                var contractName = AttributedModelServices.GetContractName(item.Item1);
                var typeIdentity = AttributedModelServices.GetTypeIdentity(item.Item1);
                batch.AddExport(new Export(contractName, new Dictionary <string, object>
                {
                    {
                        "ExportTypeIdentity",
                        typeIdentity
                    }
                }, () => item.Item2));
            }
            batch.AddExportedValue <ICompositionService>(container);
            return(batch);
        }
        public void AddExport_ReturnedComposablePart_ContainsExportDefinitionRepresentingExport()
        {
            var metadata = new Dictionary <string, object>();

            metadata["Name"] = "Value";

            CompositionBatch batch = new CompositionBatch();
            var export             = ExportFactory.Create("Contract", "Value", metadata);

            var part = batch.AddExport(export);

            Assert.Equal(1, batch.PartsToAdd.Count);

            var definition = part.ExportDefinitions.Single();

            Assert.Equal("Contract", definition.ContractName);
            Assert.Equal("Value", part.GetExportedValue(definition));
            EnumerableAssert.AreEqual(metadata, definition.Metadata);
        }
        [ActiveIssue("https://github.com/dotnet/corefx/issues/25498", TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
        public void InAdditionToCatalogTest()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            IDictionary <string, object> multMetadata = new Dictionary <string, object>();

            multMetadata["Var1"] = "mult";
            multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func <int, int, int>));
            var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func <int, int, int>) delegate(int a, int b)
                                                                        { return(a * b); }));

            CompositionBatch batch = new CompositionBatch();

            batch.AddExport(basicValue);
            container.Compose(batch);

            var exports = container.GetExports <Func <int, int, int>, ITrans_ExportableTest>("Add");

            Assert.Equal(3, exports.Count());

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "mult")
                {
                    Assert.Equal(2, export.Value(1, 2));
                }
                else if (export.Metadata.Var1 == "add")
                {
                    Assert.Equal(3, export.Value(1, 2));
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.Equal(-1, export.Value(1, 2));
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
        }
Beispiel #30
0
        public void InAdditionToCatalogTest()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            IDictionary <string, object> multMetadata = new Dictionary <string, object>();

            multMetadata["Var1"] = "mult";
            multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func <int, int, int>));
            var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func <int, int, int>) delegate(int a, int b) { return(a * b); }));

            CompositionBatch batch = new CompositionBatch();

            batch.AddExport(basicValue);
            container.Compose(batch);

            var exports = container.GetExports <Func <int, int, int>, IExportableTest>("Add");

            Assert.AreEqual(3, exports.Count(), "There should be 3 entries for 'Add'");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "mult")
                {
                    Assert.AreEqual(2, export.Value(1, 2), "1 * 2 == 2");
                }
                else if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }