public void WhenInitializingAModuleWithACatalogPendingToBeLoaded_ThenLoadsTheCatalogInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

            var serviceLocatorMock = new Mock<IServiceLocator>();
            var loggerFacadeMock = new Mock<ILoggerFacade>();

            var serviceLocator = serviceLocatorMock.Object;
            var loggerFacade = loggerFacadeMock.Object;

            compositionContainer.ComposeExportedValue(serviceLocator);
            compositionContainer.ComposeExportedValue(loggerFacade);

            var moduleInitializer = compositionContainer.GetExportedValue<IModuleInitializer>();
            var repository = compositionContainer.GetExportedValue<DownloadedPartCatalogCollection>();

            var moduleInfo = new ModuleInfo("TestModuleForInitializer", typeof(TestModuleForInitializer).AssemblyQualifiedName);

            repository.Add(moduleInfo, new TypeCatalog(typeof(TestModuleForInitializer)));

            moduleInitializer.Initialize(moduleInfo);

            ComposablePartCatalog existingCatalog;
            Assert.IsFalse(repository.TryGet(moduleInfo, out existingCatalog));

            var module = compositionContainer.GetExportedValues<IModule>().OfType<TestModuleForInitializer>().First();

            Assert.IsTrue(module.Initialized);
        }
        public void WhenInitializingAModuleWithNoCatalogPendingToBeLoaded_ThenInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

            var serviceLocatorMock = new Mock<IServiceLocator>();
            var loggerFacadeMock = new Mock<ILoggerFacade>();

            var serviceLocator = serviceLocatorMock.Object;
            var loggerFacade = loggerFacadeMock.Object;

            compositionContainer.ComposeExportedValue(serviceLocator);
            compositionContainer.ComposeExportedValue(loggerFacade);

            aggregateCatalog.Catalogs.Add(new TypeCatalog(typeof(TestModuleForInitializer)));

            var moduleInitializer = compositionContainer.GetExportedValue<IModuleInitializer>();

            var moduleInfo = new ModuleInfo("TestModuleForInitializer", typeof(TestModuleForInitializer).AssemblyQualifiedName);

            var module = compositionContainer.GetExportedValues<IModule>().OfType<TestModuleForInitializer>().First();

            Assert.IsFalse(module.Initialized);

            moduleInitializer.Initialize(moduleInfo);

            Assert.IsTrue(module.Initialized);
        }
Ejemplo n.º 3
0
        public VsPackage()
        {
            _instance = this;
            Tracer    = new OutputWindowTracer(this);

            _compositionCatalog   = new AggregateCatalog();
            _compositionContainer = new CompositionContainer(_compositionCatalog, true);
            _exportProvider       = new ExportProviderAdapter(_compositionContainer);
            _compositionContainer.ComposeExportedValue(_exportProvider);
        }
Ejemplo n.º 4
0
        public WispPlugProvider(WispManagerInterface wispManager)
        {
            AggregateCatalog catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new DirectoryCatalog("."));
            CompositionContainer container = new CompositionContainer(catalog);

            container.ComposeExportedValue("wispManager", wispManager);
            container.ComposeParts(this);
        }
Ejemplo n.º 5
0
        private void CreateBindingContainer()
        {
            // We leverage the Feature Runtime container, where all their components and extensions publish already.
            var defaultCatalog = this.componentModel.GetCatalog(NuPattern.VisualStudio.Composition.Catalog.DefaultCatalogName);
            var ourCatalog     = this.componentModel.GetCatalog(Catalog.DefaultCatalogName);

            if (defaultCatalog == null || ourCatalog == null)
            {
                throw new InvalidOperationException(Resources.BindingCompositionService_CatalogsNotAvailable);
            }

            try
            {
                // Transparently change the INuPatternCompositionService implementation for all components
                // without code changes by providing an instance earlier in the chain.
                // See http://codebetter.com/blogs/glenn.block/archive/2009/05/14/customizing-container-behavior-part-2-of-n-defaults.aspx
                this.defaultCompositionProvider = new CompositionContainer();
                defaultCompositionProvider.ComposeExportedValue <INuPatternCompositionService>(this);
                defaultCompositionProvider.ComposeExportedValue <SVsServiceProvider>((SVsServiceProvider)serviceProvider);

                // Decorated catalog of parts.
                // NOTE: caching the catalog also caches the instantiated shared parts, if any.
                this.bindingCatalog = new BindingComponentCatalog(new AggregateCatalog(ourCatalog, defaultCatalog));
                var bindingProvider = new CatalogExportProvider(this.bindingCatalog);

                this.container = new CompositionContainer(
                    defaultCompositionProvider,
                    bindingProvider,
                    componentModel.DefaultExportProvider);

                bindingProvider.SourceProvider = this.container;
            }
            catch (Exception ex)
            {
                tracer.Error(ex, Resources.BindingCompositionService_FailedToInitialize);
                throw;
            }

            // Used by the CompositionServiceBindingContext to create a new CompositionContainer over
            // this one for dynamic context resolution.
            this.container.ComposeExportedValue <ExportProvider>(container);
        }
Ejemplo n.º 6
0
    public void Execute()
    {
        using (var catalog = new AssemblyCatalog(GetType().Assembly))
            using (var container = new CompositionContainer(catalog))
            {
                container.ComposeExportedValue(ModuleDefinition);
                container.ComposeExportedValue(this);

                var directoryName = Path.GetDirectoryName(AssemblyPath);

                foreach (var targetFile in Directory.EnumerateFiles(directoryName, "*.dll"))
                {
                    if (targetFile != AssemblyPath)
                    {
                        container.GetExportedValue <AssemblyProcessor>().Execute(targetFile);
                    }
                }
                container.GetExportedValue <AssemblyProcessor>().Execute(ModuleDefinition);
            }
    }
Ejemplo n.º 7
0
        private CompositionContainer CreateCompositionContainer()
        {
            var container = new CompositionContainer(CachedInfo.Catalog);

            container.ComposeExportedValue <MockVs>(this);
            var batch = new CompositionBatch();

            container.Compose(batch);

            return(container);
        }
        public void BeforeTest()
        {
            windowManagementModule          = new WindowManagementModule();
            windowFocusEventProducer        = new WindowFocusEventProducer();
            windowMovementEventProducer     = new WindowMovementEventProducer();
            windowResizingEventProducer     = new WindowResizingEventProducer();
            windowStateChangedEventProducer = new WindowStateChangedEventProducer();

            container = new CompositionContainer();
            container.ComposeExportedValue(windowFocusEventProducer);
            container.ComposeExportedValue(windowMovementEventProducer);
            container.ComposeExportedValue(windowResizingEventProducer);
            container.ComposeExportedValue(windowStateChangedEventProducer);
            container.ComposeParts(windowManagementModule);

            nativeWindowManagement = new NativeWindowMock();

            hookNativeMethods = new HookNativeMethodsMock();
            hookNativeMethods.Initialize();
        }
Ejemplo n.º 9
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var catalog = new AggregateCatalog(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                new AssemblyCatalog(typeof(IDialogService).Assembly));

            _container = new CompositionContainer(catalog);
            _container.ComposeExportedValue(_container);
            _container.ComposeExportedValue("AppName", "Services and Drivers");
            _container.ComposeExportedValue <IUIServices>(new UIServicesDefaults());

            var vm  = _container.GetExportedValue <MainViewModel>();
            var win = new MainWindow {
                DataContext = vm
            };

            win.Show();
        }
Ejemplo n.º 10
0
        public void VerifyGetAllInstancesReturnsCorrectInstances()
        {
            string firstStringInstance  = nameof(firstStringInstance);
            string secondStringInstance = nameof(secondStringInstance);

            var container = new CompositionContainer();

            container.ComposeExportedValue(firstStringInstance);
            container.ComposeExportedValue(secondStringInstance);
            container.ComposeExportedValue(typeof(string));
            container.ComposeExportedValue(Math.PI);

            var serviceLocator = new MefServiceLocator(container);

            var instances = serviceLocator.GetAllInstances <string>();

            Assert.That(instances.ToList(), Has.Count.EqualTo(2));
            Assert.That(instances, Has.Exactly(1).EqualTo(firstStringInstance));
            Assert.That(instances, Has.Exactly(1).EqualTo(secondStringInstance));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Composes the parts.
        /// </summary>
        private void ComposeParts()
        {
            var errors = false;

            // Load the modules.
            var extensionCatalogs   = new AggregateCatalog();
            var extensionsDirectory = Path.Combine(this.HomeDirectory, "Extensions");

            // Create the extension directory if it doesn't exist.
            if (!Directory.Exists(extensionsDirectory))
            {
                Directory.CreateDirectory(extensionsDirectory);
                Logger.Debug("Missing directory {0} has been re-created.", extensionsDirectory);
            }

            foreach (var subDirectory in Directory.GetDirectories(extensionsDirectory))
            {
                var catalog = new DirectoryCatalog(subDirectory);

                try
                {
                    if (catalog.Parts.Any())
                    {
                        extensionCatalogs.Catalogs.Add(catalog);
                        Logger.Debug("Adding a new DirectoryCatalog {0}.", subDirectory);
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorException(ex, ex.Message);
                    errors = true;
                }
            }

            try
            {
                Logger.Debug("Loading composition parts.");
                var compositionContainer = new CompositionContainer(extensionCatalogs);

                compositionContainer.ComposeExportedValue(nameof(IHost), this);

                compositionContainer.ComposeParts(this);
            }
            catch (Exception ex)
            {
                Logger.ErrorException(ex, ex.Message);
                errors = true;
            }

            if (errors)
            {
                this.ShowBalloonToolTip("Loading extensions failed", "One or more extensions failed to load. Check log file for more information.", BalloonIcon.Error);
            }
        }
        public void PartsShouldHaveImportsSatisfiedBeforeBeingUsedToSatisfyRecomposableImports()
        {
            var container   = new CompositionContainer();
            var fooOptional = new FooWithOptionalImport();

            container.ComposeParts(fooOptional);
            container.ComposeExportedValue <string>("FooSimpleImport", "NotNullOrEmpty");
            container.ComposeParts(new FooWithSimpleImport());

            Assert.True(!string.IsNullOrEmpty(fooOptional.OptionalImport.SimpleValue));
        }
Ejemplo n.º 13
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Catalog = new AggregateCatalog(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "*.modules.*.dll"));

            Container = new CompositionContainer(Catalog);
            var ui = new UIServicesDefaults();

            Container.ComposeExportedValue <IUIServices>(ui);
            Container.ComposeExportedValue(Container);
            var vm  = Container.GetExportedValue <MainViewModel>();
            var win = new MainWindow {
                DataContext = vm
            };

            win.Show();
            ui.MessageBoxService.SetOwner(win);
        }
Ejemplo n.º 14
0
        public IEnumerable <Tuple <string, T> > GetModules()
        {
            var container = new CompositionContainer(_catalog);

            container.ComposeExportedValue(_catalog);

            var exports = container.GetExports <T, Dictionary <string, object> >().ToList();
            var modules =
                exports.Select(export => new Tuple <string, T>(export.Metadata[_nameAttribute].ToString(), export.Value));

            return(modules);
        }
Ejemplo n.º 15
0
    public void TestConstructorInjectionWithMultipleConstructors()
    {
        string ExpectedConstructorParameterValue = "42";
        var    catalog   = new TypeCatalog(typeof(Foo), typeof(FooImporter));
        var    container = new CompositionContainer(catalog);

        container.ComposeExportedValue <string>(ConstructorParameterContract, ExpectedConstructorParameterValue);
        var fooImporter = container.GetExportedValue <FooImporter>();

        Assert.AreEqual(1, fooImporter.FooList.Count, "Expect a single IFoo import in the list");
        Assert.AreEqual(ExpectedConstructorParameterValue, fooImporter.FooList[0].Value.ConstructorParameter, "Expected foo's ConstructorParameter to have the correct value.");
    }
Ejemplo n.º 16
0
        protected void Application_Start()
        {
            AggregateCatalog catalog          = new AggregateCatalog();
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(AssemblyDirectory);

            catalog.Catalogs.Add(directoryCatalog);
            CompositionContainer = new CompositionContainer(catalog);
            CompositionContainer.ComposeExportedValue("RedisConnString", ConfigurationManager.AppSettings["RedisConnectionString"]);
            CompositionContainer.ComposeParts(this);

            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
Ejemplo n.º 17
0
        private static JobRunner LoadJobRunner(Settings settings)
        {
            AssemblyCatalog catalog   = new AssemblyCatalog(typeof(WorkerRole).Assembly);
            var             container = new CompositionContainer(catalog);

            // Load settings
            settings = settings ?? new Settings();
            container.ComposeExportedValue(settings);

            // Get the job runner
            return(container.GetExportedValue <JobRunner>());
        }
Ejemplo n.º 18
0
        public void ShouldForwardResolveToInnerContainerWhenKeyIsUsed()
        {
            object myInstance = new object();

            CompositionContainer compositionContainer = new CompositionContainer();

            compositionContainer.ComposeExportedValue <object>("key", myInstance);

            IServiceLocator containerAdapter = new MefServiceLocatorAdapter(compositionContainer);

            Assert.AreSame(myInstance, containerAdapter.GetInstance(typeof(object), "key"));
        }
Ejemplo n.º 19
0
        public AppBootstrapper()
        {
            var path    = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(AppBootstrapper).Assembly));
            catalog.Catalogs.Add(new DirectoryCatalog(path));
            var isolatingCatalog = new IsolatingCatalog(catalog);

            _container = new CompositionContainer(isolatingCatalog);
            _container.ComposeExportedValue(_container);
        }
        public void Throw_If_Crash_Dump_Cannot_Be_Loaded()
        {
            // arrange
            var container = new CompositionContainer();

            container.ComposeExportedValue <IConverter>(new Converter());
            Action mightThrow = () => new CoreComponentFactory(container, new FileInfo(@"C:\this\doesnt\exist.dmp"));

            // act
            // assert
            mightThrow.Should().Throw <ApplicationException>();
        }
Ejemplo n.º 21
0
        public void BeforeTest()
        {
            //initialize module, producers and configuration
            mouseModule              = new MouseModule();
            mouseClickEventProducer  = new MouseClickEventProducer();
            mouseMoveEventProducer   = new MouseMoveEventProducer();
            mouseScrollEventProducer = new MouseScrollEventProducer();
            mouseModuleConfiguration = new TestMouseModuleConfiguration();

            // initialize the container and fulfill the MEF inports exports
            container = new CompositionContainer();
            container.ComposeExportedValue(mouseClickEventProducer);
            container.ComposeExportedValue(mouseMoveEventProducer);
            container.ComposeExportedValue(mouseScrollEventProducer);
            container.ComposeExportedValue(mouseModuleConfiguration);
            container.ComposeParts(mouseModule);

            //initialzie the hookNativeMethodsMock
            hookNativeMethodsMock = new HookNativeMethodsMock();
            hookNativeMethodsMock.Initialize();
        }
Ejemplo n.º 22
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var catalog = new AggregateCatalog(new DeploymentCatalog());

            _extension = new DeploymentCatalog("SilverlightMEF.Extensions.xap");
            catalog.Catalogs.Add(_extension);
            var container = new CompositionContainer(catalog);

            CompositionHost.Initialize(container);
            container.ComposeExportedValue <ILaunchInterface>(this);
            CompositionInitializer.SatisfyImports(this);
        }
        public ConceptsModule(IRegionManager regionManager)
        {
            RegionManager = regionManager;
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ConceptsModule).Assembly));
            _localContainer = new CompositionContainer(catalog);

            _localContainer.ComposeExportedValue(RegionManager);

            _localContainer.ComposeParts(this);
        }
Ejemplo n.º 24
0
        void Inner()
        {
            using (var catalog = new AssemblyCatalog(GetType().Assembly))
                using (var container = new CompositionContainer(catalog))
                {
                    container.ComposeExportedValue(this);
                    container.ComposeExportedValue(BuildEngine);
                    container.ComposeExportedValue(logger);
                    CheckForInvalidConfig();
                    container.GetExportedValue <TargetPathFinder>().Execute();

                    logger.LogMessage(string.Format("\tTargetPath: {0}", TargetPath));


                    container.GetExportedValue <AssemblyResolver>().Execute();
                    var moduleReader = container.GetExportedValue <ModuleReader>();
                    moduleReader.Execute();

                    var fileChangedChecker = container.GetExportedValue <FileChangedChecker>();
                    if (!fileChangedChecker.ShouldStart())
                    {
                        return;
                    }

                    container.GetExportedValue <MsCoreReferenceFinder>().Execute();

                    container.GetExportedValue <AssemblyLoaderImporter>().Execute();
                    container.GetExportedValue <ModuleLoaderImporter>().Execute();
                    container.GetExportedValue <DependencyFinder>().Execute();
                    container.GetExportedValue <ProjectKeyReader>().Execute();
                    container.GetExportedValue <ResourceCaseFixer>().Execute();
                    using (var resourceEmbedder = container.GetExportedValue <ResourceEmbedder>())
                    {
                        resourceEmbedder.Execute();
                        var savePath = GetSavePath();
                        container.GetExportedValue <ModuleWriter>().Execute(savePath);
                    }
                    container.GetExportedValue <ReferenceDeleter>().Execute();
                }
        }
Ejemplo n.º 25
0
        private void SetupDefaultServices(CompositionContainer mefContainer)
        {
            if (mefContainer.GetExportedValueOrDefault <IResponseParser>() == null)
            {
                mefContainer.ComposeExportedValue <IResponseParser>(new ResponseParser());
            }

            if (mefContainer.GetExportedValueOrDefault <IBotServices>() == null)
            {
                mefContainer.ComposeExportedValue <IBotServices>(new SlackSendQueueService());
            }

            if (mefContainer.GetExportedValueOrDefault <IBotState>() == null)
            {
                mefContainer.ComposeExportedValue <IBotState>(new BotState());
            }

            if (mefContainer.GetExportedValueOrDefault <ISlackApi>() == null)
            {
                mefContainer.ComposeExportedValue <ISlackApi>(SlackApi.Create(this.apiKey));
            }

            if (mefContainer.GetExportedValueOrDefault <IBackOffStrategy>() == null)
            {
                mefContainer.ComposeExportedValue <IBackOffStrategy>(new BackOffRetry());
            }

            if (mefContainer.GetExportedValueOrDefault <ILog>() == null)
            {
                mefContainer.ComposeExportedValue <ILog>(LogManager.GetLogger(typeof(ISlackBot)));
            }
        }
Ejemplo n.º 26
0
        private void Initialize(IFileSystem fileSystem, IConsole console)
        {
            using (var catalog = new AggregateCatalog(new AssemblyCatalog(GetType().Assembly)))
            {
                if (!IgnoreExtensions)
                {
                    AddExtensionsToCatalog(catalog);
                }
                using (var container = new CompositionContainer(catalog))
                {
                    var settings             = GetCommandLineSettings(fileSystem);
                    var defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl);

                    var officialPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl, NuGetResources.OfficialPackageSourceName);
                    var v1PackageSource       = new PackageSource(NuGetConstants.V1FeedUrl, NuGetResources.OfficialPackageSourceName);
                    var legacyV2PackageSource = new PackageSource(NuGetConstants.V2LegacyFeedUrl, NuGetResources.OfficialPackageSourceName);

                    var packageSourceProvider = new PackageSourceProvider(
                        settings,
                        new[] { defaultPackageSource },
                        new Dictionary <PackageSource, PackageSource> {
                        { v1PackageSource, officialPackageSource },
                        { legacyV2PackageSource, officialPackageSource }
                    }
                        );

                    // Register an additional provider for the console specific application so that the user
                    // will be prompted if a proxy is set and credentials are required
                    var credentialProvider = new SettingsCredentialProvider(new ConsoleCredentialProvider(), packageSourceProvider, console);
                    HttpClient.DefaultCredentialProvider = credentialProvider;

                    container.ComposeExportedValue <IConsole>(console);
                    container.ComposeExportedValue <ISettings>(settings);
                    container.ComposeExportedValue <IPackageRepositoryFactory>(new NuGet.Common.CommandLineRepositoryFactory());
                    container.ComposeExportedValue <IPackageSourceProvider>(packageSourceProvider);
                    container.ComposeExportedValue <ICredentialProvider>(credentialProvider);
                    container.ComposeParts(this);
                }
            }
        }
Ejemplo n.º 27
0
        private void LoadProcesses()
        {
            if ((_configuration.Processes == null) || !_configuration.Processes.Any())
            {
                _log.Warning($"{Name}: No processes configured.");
                return;
            }

            // TODO: Implement appdomain isolation for process assemblies
            try
            {
                var catalog = new AggregateCatalog();

                // Add the base directories to the catalog:
                catalog.Catalogs.Add(new DirectoryCatalog(".", "*.dll"));

                if (Directory.Exists(AssemblyPath))
                {
                    catalog.Catalogs.Add(new DirectoryCatalog(AssemblyPath, "*.dll"));
                }

                // Add each process directory to the catalog (if they exist):
                foreach (var process in _configuration.Processes)
                {
                    var path = Path.Combine(AssemblyPath, process.Name);
                    if (!Directory.Exists(path))
                    {
                        continue;
                    }

                    catalog.Catalogs.Add(new DirectoryCatalog(path, "*.dll"));
                }

                var container = new CompositionContainer(catalog);

                // HTTP interface service should be populated where needed:
                container.ComposeExportedValue("IHttpInterfaceService", _httpInterface as IHttpInterfaceService);
                container.ComposeParts(this);
            }
            catch (ReflectionTypeLoadException ex)
            {
                var loaderExceptions = ex.LoaderExceptions != null
                    ? string.Join(", ", ex.LoaderExceptions.Select(x => x.Message))
                    : string.Empty;

                _log.Error($"{Name}: Could not load process assemblies: {loaderExceptions}", ex);
            }
            catch (Exception ex)
            {
                _log.Error($"{Name}: Could not load process assemblies.", ex);
            }
        }
Ejemplo n.º 28
0
        public void RegisterInstanceAndResolve()
        {
            ServiceAdd instanceOfService = new ServiceAdd();

            using (CompositionContainer mefContainer = new CompositionContainer())
            {
                mefContainer.ComposeExportedValue <IService>(instanceOfService);

                IService service = mefContainer.GetExportedValue <IService>();
                //IService service = mefContainer.GetExport<IService>().Value;
                Assert.That(service.Calc(1, 2), Is.EqualTo(3));
            }
        }
Ejemplo n.º 29
0
        CompositionContainer CreateCompositionContainer()
        {
            var compositionServices = new CompositionServices();
            var exportProvider      = compositionServices.GetExportProvider();

            var compositionContainer      = new CompositionContainer(exportProvider);
            var gitHubServiceProvider     = exportProvider.GetExportedValue <IGitHubServiceProvider>();
            var externalShowDialogService = new ExternalShowDialogService(gitHubServiceProvider, this);

            compositionContainer.ComposeExportedValue <IShowDialogService>(externalShowDialogService);

            return(compositionContainer);
        }
Ejemplo n.º 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            AggregateCatalog catalog          = new AggregateCatalog();
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(AssemblyDirectory);

            catalog.Catalogs.Add(directoryCatalog);
            CompositionContainer = new CompositionContainer(catalog);
            CompositionContainer.ComposeExportedValue("RedisConnString", Configuration.GetValue <string>("RedisConnectionString"));
            CompositionContainer.ComposeParts(this);

            services.AddControllers();
            services.AddApplicationInsightsTelemetry();
        }
Ejemplo n.º 31
0
        private INuPatternCompositionService CreateCompositionService(IGuidanceExtension extension, string extensionId)
        {
            var extensionContainer = new CompositionContainer(extensionsGlobalContainer);

            // Expose IGuidanceExtension to the container
            extensionContainer.ComposeExportedValue(extension);
            extensionContainer.ComposeExportedValue(InstalledGuidanceExtensions.First(r => r.ExtensionId == extensionId));

            extensionContainer.ComposeExportedValue <ExportProvider>(extensionContainer);

            var compositionService = new NuPatternCompositionService(extensionContainer);

            // Expose IGuidanceExtensionCompositionService to the container
            extensionContainer.ComposeExportedValue <INuPatternCompositionService>(compositionService);

            // Satisfy imports at this level, so that the right guidance extension-level stuff is injected instead
            // (i.e. the guidance extension might have specified an import of the IGudianceExtensionCompositionService and
            // would have gotten the global one.
            compositionService.SatisfyImportsOnce(extension);

            return(compositionService);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Build MEF catalog and create composition container
        /// </summary>
        /// <returns>Configured composition container</returns>
        private CompositionContainer CreateCompositionContainer()
        {
            // In addition to explicitly exported classes, auto-export all web api controllers
            var rb = new RegistrationBuilder();

            rb.ForTypesMatching <ApiController>(t => typeof(ApiController).IsAssignableFrom(t) && t.Name.EndsWith("Controller"))
            .Export()
            .SetCreationPolicy(CreationPolicy.NonShared);
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), rb);

            // Create composition container
            var container = new CompositionContainer(catalog);

            container.ComposeExportedValue <INameGenerator>(new NameGenerator());
            container.ComposeExportedValue(new BooksDemoDataOptions
            {
                MinimumNumberOfBooks = Int32.Parse(ConfigurationManager.AppSettings["MinimumNumberOfBooks"]),
                MaximumNumberOfBooks = Int32.Parse(ConfigurationManager.AppSettings["MaximumNumberOfBooks"])
            });

            return(container);
        }
 private static Mock<IModuleManager> SetupModuleManager(CompositionContainer container)
 {
     Mock<IModuleManager> mockModuleManager = new Mock<IModuleManager>();
     container.ComposeExportedValue<IModuleManager>(mockModuleManager.Object);
     return mockModuleManager;
 }
        public void DeclaredModuleWithTypeInUnreferencedAssemblyIsUpdatedWithTypeNameFromExportAttribute()
        {
            AggregateCatalog aggregateCatalog = new AggregateCatalog();
            CompositionContainer compositionContainer = new CompositionContainer(aggregateCatalog);

            var mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>();
            mockFileTypeLoader.Setup(tl => tl.CanLoadModuleType(It.IsAny<ModuleInfo>())).Returns(true);


            ModuleCatalog moduleCatalog = new ModuleCatalog();
            ModuleInfo moduleInfo = new ModuleInfo { ModuleName = "MefModuleOne", ModuleType = "some type" };
            moduleCatalog.AddModule(moduleInfo);

            compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog);
            compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object);

            bool wasInit = false;
            var mockModuleInitializer = new Mock<IModuleInitializer>();
            mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true);

            var mockLoggerFacade = new Mock<ILoggerFacade>();

            MefModuleManager moduleManager = new MefModuleManager(
                mockModuleInitializer.Object,
                moduleCatalog,
                mockLoggerFacade.Object);

            compositionContainer.SatisfyImportsOnce(moduleManager);
            moduleManager.Run();

            Assert.IsFalse(wasInit);

            AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll());
            aggregateCatalog.Catalogs.Add(assemblyCatalog);

            compositionContainer.SatisfyImportsOnce(moduleManager);

            mockFileTypeLoader.Raise(tl => tl.LoadModuleCompleted += null, new LoadModuleCompletedEventArgs(moduleInfo, null));

            Assert.AreEqual("MefModulesForTesting.MefModuleOne, MefModulesForTesting, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", moduleInfo.ModuleType);
            Assert.IsTrue(wasInit);
        }
        private static void SetupRegionBehaviorAdapters(CompositionContainer container)
        {
            var regionBehaviorFactory = new RegionBehaviorFactory(new MefServiceLocatorAdapter(container));
#if SILVERLIGHT
            container.ComposeExportedValue<TabControlRegionAdapter>(new TabControlRegionAdapter(regionBehaviorFactory));
#endif

            container.ComposeExportedValue<SelectorRegionAdapter>(new SelectorRegionAdapter(regionBehaviorFactory));
            container.ComposeExportedValue<ItemsControlRegionAdapter>(new ItemsControlRegionAdapter(regionBehaviorFactory));
            container.ComposeExportedValue<ContentControlRegionAdapter>(new ContentControlRegionAdapter(regionBehaviorFactory));
            container.ComposeExportedValue<RegionAdapterMappings>(new RegionAdapterMappings());
        }
        public void ModuleInUnreferencedAssemblyInitializedByModuleInitializer()
        {
            AssemblyCatalog assemblyCatalog = new AssemblyCatalog(GetPathToModuleDll());
            CompositionContainer compositionContainer = new CompositionContainer(assemblyCatalog);

            ModuleCatalog moduleCatalog = new ModuleCatalog();

            Mock<MefFileModuleTypeLoader> mockFileTypeLoader = new Mock<MefFileModuleTypeLoader>();

            compositionContainer.ComposeExportedValue<IModuleCatalog>(moduleCatalog);
            compositionContainer.ComposeExportedValue<MefFileModuleTypeLoader>(mockFileTypeLoader.Object);

            bool wasInit = false;
            var mockModuleInitializer = new Mock<IModuleInitializer>();
            mockModuleInitializer.Setup(x => x.Initialize(It.IsAny<ModuleInfo>())).Callback(() => wasInit = true);

            var mockLoggerFacade = new Mock<ILoggerFacade>();

            MefModuleManager moduleManager = new MefModuleManager(
                mockModuleInitializer.Object,
                moduleCatalog,
                mockLoggerFacade.Object);

            compositionContainer.SatisfyImportsOnce(moduleManager);

            moduleManager.Run();

            Assert.IsTrue(wasInit);
        }