Example #1
0
        public void SingletonBehavior()
        {
            TypeCatalog          catalog   = new TypeCatalog(typeof(SingletonExport <,>));
            CompositionContainer container = new CompositionContainer(catalog);

            SingletonExportExportCount.Count = 0;

            var exports = container.GetExportedValues <IExport <IFoo, IBar> >();

            Assert.Equal(1, exports.Count());
            // only one instance of the SingletonExport<,> is created
            Assert.Equal(1, SingletonExportExportCount.Count);

            exports = container.GetExportedValues <IExport <IFoo, IBar> >();
            Assert.Equal(1, exports.Count());
            // still only one instance of the SingletonExport<,> is created
            Assert.Equal(1, SingletonExportExportCount.Count);

            var import = new SingletonImport <IFoo, IBar>();

            container.SatisfyImportsOnce(import);
            // still only one instance of the SingletonExport<,> is created
            Assert.Equal(1, SingletonExportExportCount.Count);

            import = new SingletonImport <IFoo, IBar>();
            container.SatisfyImportsOnce(import);
            // still only one instance of the SingletonExport<,> is created
            Assert.Equal(1, SingletonExportExportCount.Count);

            var import2 = new SingletonImport <IBar, IFoo>();

            container.SatisfyImportsOnce(import2);
            // two instances of the SingletonExport<,> is created
            Assert.Equal(2, SingletonExportExportCount.Count);
        }
Example #2
0
        public override IController CreateController(
            RequestContext requestContext,
            string controllerName)
        {
            IController controller =
                base.CreateController(requestContext, controllerName);

            _container.SatisfyImportsOnce(controller); // MEF injection
            return(controller);
        }
Example #3
0
        public ICompositionFactory <T> GetInstanceFactory <T>() where T : class
        {
            var factory = new MefCompositionFactory <T>();

            Container.SatisfyImportsOnce(factory);
            if (factory.ExportFactory == null)
            {
                throw new CompositionException(string.Format(StringResources.NoExportFound, typeof(T)));
            }

            return(factory);
        }
        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);
        }
Example #5
0
        public void ConfigureContainerLocator()
        {
            var assemblyCatalog  = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var directoryCatalog = new DirectoryCatalog(@".\", "*.dll");
            var compositeCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog);

            if (Directory.Exists(@".\Addins"))
            {
                var addinsCatalog = new DirectoryCatalog(@".\Addins", "*.dll");
                compositeCatalog.Catalogs.Add(addinsCatalog);
            }
            var compositeContainer = new CompositionContainer(compositeCatalog);

            ContainerLocator.Container.RegisterCatalog(compositeCatalog);

            #region ViewModels

            ContainerLocator.Container.RegisterType <IMainWindowViewModel, MainWindowViewModel>();
            ContainerLocator.Container.RegisterType <ITestDetailsViewModel, TestDetailsWindowViewModel>();

            #endregion

            ContainerLocator.Container.RegisterInstance(EventAggregator.Instance);
            ContainerLocator.Container.RegisterType <ITestManager, TestManager>();

            #region Locators

            ContainerLocator.Container.RegisterType <IViewModelLocator, ViewModelLocator>();
            ContainerLocator.Container.RegisterInstance <IWindowService>(GetWindowService());

            #endregion

            #region Serializer

            IViewModelStateSerializer stateSerializer = new ViewModelStateCompositeSerializer();
            compositeContainer.SatisfyImportsOnce(stateSerializer);
            ContainerLocator.Container.RegisterInstance(stateSerializer);

            #endregion

            #region Test Analyser

            ITestAnalyser testAnalyser = new TestCompositeAnalyser();
            compositeContainer.SatisfyImportsOnce(testAnalyser);
            ContainerLocator.Container.RegisterInstance(testAnalyser);

            #endregion
        }
Example #6
0
    public Program()
    {
        var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly);
        var container       = new CompositionContainer(assemblyCatalog);

        container.SatisfyImportsOnce(this);
    }
Example #7
0
        static ScriptureProvider()
        {
            var scriptureProvider = new ScriptureProvider();
            var catalog           = new AggregateCatalog();

            //Adds all the parts found in the same assembly as the ScriptureProvider class
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ScriptureProvider).Assembly));
            //Adds all the parts found in assemblies ending in Plugin.dll that reside in the FLExExe path
            var extensionPath = Path.Combine(Path.GetDirectoryName(FwDirectoryFinder.FlexExe));

            catalog.Catalogs.Add(new DirectoryCatalog(extensionPath, "*Plugin.dll"));
            //Create the CompositionContainer with the parts in the catalog
            var container = new CompositionContainer(catalog);

            container.SatisfyImportsOnce(scriptureProvider);

            // Choose the ScriptureProvider that reports the newest version
            // (If both Paratext 7 and 8 are installed, the plugin handling 8 will be used)
            foreach (var provider in scriptureProvider._potentialScriptureProviders)
            {
                if (_scriptureProvider == null || provider.Value.MaximumSupportedVersion > _scriptureProvider.MaximumSupportedVersion)
                {
                    _scriptureProvider = provider.Value;
                }
            }
#if DEBUG
            if (_scriptureProvider == null)
            {
                throw new ApplicationException("No scripture providers discovered by MEF");
            }
#endif // DEBUG
            InitializeIfNeeded();
        }
        /// <summary>
        /// Register all the ICarrierClusterStream and ICarrierStream implementations defined in the providerDirectory
        /// </summary>
        /// <param name="providerDirectory">Provider directory to scan for carrier implmentations</param>
        /// <exception cref="Steganography.NoCarrierClusterStreamsFoundException">
        ///		Thrown when no ICarrierClusterStreams are found and cluster streams are required.
        ///	</exception>
        /// <exception cref="Steganography.NoCarrierStreamsFoundException">Thrown when no ICarrierStreams are found.</exception>
        private void RegisterCarrierProviders(string providerDirectory)
        {
            CompositionContainer container = new CompositionContainer(
                new DirectoryCatalog(providerDirectory), CompositionOptions.DisableSilentRejection);

            container.SatisfyImportsOnce(this);

            if (_requireClusterStreams && _carrierClusterStreams.Count() == 0)
            {
                throw new NoCarrierClusterStreamsFoundException(providerDirectory);
            }

            if (_carrierStreams.Count() == 0)
            {
                throw new NoCarrierStreamsFoundException(providerDirectory);
            }

            if (_carrierClusterStreams.Count() > 0)
            {
                _carrierClusterStreams.ToList()
                .AsParallel()
                .ForAll(RegisterCarrierClusters);
            }

            _carrierStreams.ToList()
            .AsParallel()
            .ForAll(RegisterCarrierStreams);
        }
Example #9
0
        public AddInController(IXExtension ext)
        {
            AppDomain.CurrentDomain.ResolveBindingRedirects(new LocalAppConfigBindingRedirectReferenceResolver());

            m_HostModule = new AddInHostModule(ext);

            m_Ext = ext;

            var cmdGrp = ext.CommandManager.AddCommandGroup <CadPlusCommands_e>();

            cmdGrp.CommandClick += OnCommandClick;

            var modulesDir = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "Modules");

            var catalog = CreateDirectoryCatalog(modulesDir, "*.Module.dll");

            var container = new CompositionContainer(catalog);

            container.SatisfyImportsOnce(this);

            if (m_Modules?.Any() == true)
            {
                foreach (var module in m_Modules)
                {
                    module.Load(ext);
                }
            }
        }
Example #10
0
        internal DocumentCache(string documentDirectoryPath, string templateDirectoryPath, TimeSpan documentLifespan)
        {
            if (!Directory.Exists(documentDirectoryPath))
            {
                throw new DirectoryNotFoundException("Could not find the document directory at \"" + documentDirectoryPath + "\".");
            }

            if (!Directory.Exists(templateDirectoryPath))
            {
                throw new DirectoryNotFoundException("Could not find the template directory at \"" + templateDirectoryPath + "\".");
            }

            this.documentDirectoryPath = documentDirectoryPath;
            this.templateDirectoryPath = templateDirectoryPath;
            this.DocumentLifespan      = documentLifespan;

            var catalog   = new DirectoryCatalog(templateDirectoryPath);
            var container = new CompositionContainer(catalog);

            container.SatisfyImportsOnce(this);

            if (this.DocumentTemplates.Length == 0)
            {
                throw new ArgumentException("Could not find any templates in the provided directory.", "templateDirectoryPath");
            }

            var pdfDocuments = Directory.GetFiles(documentDirectoryPath, "*.pdf");

            foreach (var document in pdfDocuments)
            {
                var base64Hash = Path.GetFileNameWithoutExtension(document);
                var hash       = GetHashArray(base64Hash);
                this.cachedDocuments.TryAdd(hash, new CachedDocument(document));
            }
        }
Example #11
0
        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            var job = _simpleFactory.NewJob(bundle, scheduler);

            _container.SatisfyImportsOnce(job);
            return(job);
        }
Example #12
0
        private static void Load(ComposablePartCatalog catalog)
        {
            if (_instance == null)
            {
                _instance = new ImplementationManager();
            }

            //just because we load new implementations doesn't mean we should throw away the old ones
            var old = _instance.Implementations?.ToArray();

            using (CompositionContainer container = new CompositionContainer(catalog))
            {
                //bring in the new ones
                container.SatisfyImportsOnce(_instance);

                //but also bring in any old ones that we don't have in the new load
                if (old != null)
                {
                    foreach (IImplementation o in old)
                    {
                        if (_instance.Implementations.All(i => i.GetType() != o.GetType()))
                        {
                            _instance.Implementations.Add(o);
                        }
                    }
                }
            }
        }
        private void InitializePlugins()
        {
            // We look for plugins in our own assembly and in any DLLs that live next to our EXE.
            // We could force all plugins to be in a "Plugins" directory, but it seems more straightforward
            // to just leave everything in one directory
            var builtinPlugins  = new AssemblyCatalog(GetType().Assembly);
            var externalPlugins = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

            _catalog   = new AggregateCatalog(builtinPlugins, externalPlugins);
            _container = new CompositionContainer(_catalog);

            try
            {
                _container.SatisfyImportsOnce(this);
            }
            catch (CompositionException ex)
            {
                if (_log.IsErrorEnabled)
                {
                    _log.ErrorFormat("MEF Composition Exception: {0}", ex.Message);

                    var errors = String.Join("\n    ", ex.Errors.Select(x => x.Description));
                    _log.ErrorFormat("Composition Errors: {0}", errors);
                }
                throw;
            }
        }
Example #14
0
        private void LoadPlugIn()
        {
            // 获取当前程序集
            //Assembly assCurr = Assembly.GetExecutingAssembly();

            // 确定组件搜索范围
            //AssemblyCatalog catalog = new AssemblyCatalog(assCurr);
            DirectoryCatalog catalog = new DirectoryCatalog(@"plugin");

            container = new CompositionContainer(catalog);

            //Fill the imports of this object
            //try
            //{
            container.SatisfyImportsOnce(this);
            //}
            //catch (CompositionException compositionException)
            //{
            //    Console.WriteLine(compositionException.ToString());
            //}


            //// 获取已发现的组件
            //var components = container.GetExportedValues<IDaqDevice<double>>();

            //// 分别调用一下
            //foreach (IDaqDevice<double> m in components)
            //{
            //    m.Initial();
            //}
        }
        public void UnknownExportedModuleIsAddedAndInitializedByModuleInitializer()
        {
            var aggregateCatalog     = new AggregateCatalog();
            var compositionContainer = new CompositionContainer(aggregateCatalog);

            var moduleCatalog = new ModuleCatalog();

            var mockModuleTypeLoader = new Mock <MefXapModuleTypeLoader>(new DownloadedPartCatalogCollection());

            compositionContainer.ComposeExportedValue <IModuleCatalog>(moduleCatalog);
            compositionContainer.ComposeExportedValue <MefXapModuleTypeLoader>(mockModuleTypeLoader.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>();

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

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

            compositionContainer.SatisfyImportsOnce(moduleManager);

            moduleManager.Run();

            Assert.IsTrue(wasInit);
            Assert.IsTrue(moduleCatalog.Modules.Any(mi => mi.ModuleName == "TestMefModule"));
        }
 public IEnumerable <ToolStripItem> GetExtensionMenuItems()
 {
     //for now we're not doing real extension dlls, just kind of faking it. So we will limit this load
     //to books we know go with this currently "built-in" "extension" for SIL LEAD's SHRP Project.
     //TODO: this should work, but it doesn't because BookInfo.BookLineage isn't working: if (SHRP_PupilBookExtension.ExtensionIsApplicable(BookSelection.CurrentSelection.BookInfo.BookLineage))
     if (SHRP_PupilBookExtension.ExtensionIsApplicable(BookSelection.CurrentSelection.GetBookLineage()))
     {
         //load any extension assembly found in the template's root directory
         //var catalog = new DirectoryCatalog(this.BookSelection.CurrentSelection.FindTemplateBook().FolderPath, "*.dll");
         var catalog   = new AssemblyCatalog(Assembly.GetExecutingAssembly());
         var container = new CompositionContainer(catalog);
         //inject what we have to offer for the extension to consume
         container.ComposeExportedValue <string>("PathToBookFolder", BookSelection.CurrentSelection.FolderPath);
         container.ComposeExportedValue <string>("Language1Iso639Code", _collectionSettings.Language1Iso639Code);
         container.ComposeExportedValue <Func <IEnumerable <HtmlDom> > >(GetPageDoms);
         //  container.ComposeExportedValue<Func<string>>("pathToPublishedHtmlFile",GetFileForPrinting);
         container.ComposeExportedValue <Action <int, int, HtmlDom, Action <Image>, Action <Exception> > >(GetThumbnailAsync);
         container.SatisfyImportsOnce(this);
         return(_getExtensionMenuItems == null ? new List <ToolStripItem>() : _getExtensionMenuItems());
     }
     else
     {
         return(new List <ToolStripMenuItem>());
     }
 }
        public MEFViewModelResolver()
        {
            var catalog   = new AssemblyCatalog(GetType().Assembly);
            var container = new CompositionContainer(catalog);

            container.SatisfyImportsOnce(this);
        }
Example #18
0
        private static List <IDatabaseModule> FindModules(CompositionContainer container)
        {
            try
            {
                var moduleContainer = new ModuleContainer();
                container.SatisfyImportsOnce(moduleContainer);

                if (moduleContainer.Modules != null)
                {
                    var modules = new List <IDatabaseModule>();

                    foreach (var lModule in moduleContainer.Modules)
                    {
                        try
                        {
                            var module = lModule.Value;
                            modules.Add(module);
                        }
                        catch (Exception ex)
                        {
                            log.Error(ex, "Module Initialization Error");
                        }
                    }

                    return(modules);
                }
            }
            catch (ReflectionTypeLoadException ex) { log.Error(ex); }
            catch (UnauthorizedAccessException ex) { log.Error(ex); }
            catch (Exception ex) { log.Error(ex); }

            return(null);
        }
        public void CanComposeExportsFromPythonCodeWithDecorator()
        {
            var pythonCode =
                @"
@export(IItemSource)
class StringItemSource(BasePythonItemSource):
    def GetAllItems(self):
        return [""Item 1"", ""Item 2"", ""Item 3""]
";

            var _engine       = Python.CreateEngine();
            var script        = _engine.CreateScriptSourceFromString(pythonCode);
            var typeExtractor = new ExtractTypesFromScript(_engine);
            var exports       = typeExtractor.GetPartsFromScript(script, IronPythonCommandsMefExport.InitialScopeTypes).ToList();

            var container = new CompositionContainer();
            var batch     = new CompositionBatch(exports, new ComposablePart[] {});

            container.Compose(batch);

            var instance = new MockImporter();

            container.SatisfyImportsOnce(instance);

            Assert.Equal(1, instance.ItemSources.Count());
        }
Example #20
0
 private void AddResourceImpl(IEnumerable <IResource> formats, CompositionContainer container)
 {
     foreach (var impl in formats)
     {
         try
         {
             var part = AttributedModelServices.CreatePart(impl);
             if (part.ImportDefinitions.Any())
             {
                 container.SatisfyImportsOnce(part);
             }
         }
         catch (Exception X)
         {
             System.Diagnostics.Trace.WriteLine(X.Message, impl.Tag);
         }
         foreach (var ext in impl.Extensions)
         {
             m_extension_map.Add(ext.ToUpperInvariant(), impl);
         }
         foreach (var signature in impl.Signatures)
         {
             m_signature_map.Add(signature, impl);
         }
     }
 }
Example #21
0
        private void ComposeParts()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            _compositionContainer = new CompositionContainer(catalog);
            _compositionContainer.SatisfyImportsOnce(this);
        }
Example #22
0
        private static List <IInterfacePlugin> LoadPlugins(string path)
        {
            //recursive search

            List <IInterfacePlugin> loadedPlugins = new List <IInterfacePlugin>();

            foreach (string folder in Directory.GetDirectories(path))
            {
                loadedPlugins.AddRange(LoadPlugins(folder));
            }


            DirectoryCatalog catalog = new DirectoryCatalog(path, "*.dll");

            CompositionContainer container = new CompositionContainer(catalog);

            PluginWrapper wrapper = new PluginWrapper();

            container.SatisfyImportsOnce(wrapper);

            if (wrapper.LoadedPlugins != null)
            {
                loadedPlugins.AddRange(wrapper.LoadedPlugins);
            }

            return(loadedPlugins);
        }
Example #23
0
 public IEnumerable <ToolStripItem> GetExtensionMenuItems()
 {
     //for now we're not doing real extension dlls, just kind of faking it. So we will limit this load
     //to books we know go with this currently "built-in" "extension" for SIL LEAD's SHRP Project.
     if (SHRP_PupilBookExtension.ExtensionIsApplicable(BookSelection.CurrentSelection))
     {
         //load any extension assembly found in the template's root directory
         //var catalog = new DirectoryCatalog(this.BookSelection.CurrentSelection.FindTemplateBook().FolderPath, "*.dll");
         var catalog   = new AssemblyCatalog(Assembly.GetExecutingAssembly());
         var container = new CompositionContainer(catalog);
         //inject what we have to offer for the extension to consume
         container.ComposeExportedValue <string>("PathToBookFolder", BookSelection.CurrentSelection.FolderPath);
         container.ComposeExportedValue <string>("Language1Iso639Code", _currentlyLoadedBook.BookData.Language1.Iso639Code);
         container.ComposeExportedValue <Func <IEnumerable <HtmlDom> > >(GetPageDoms);
         //  container.ComposeExportedValue<Func<string>>("pathToPublishedHtmlFile",GetFileForPrinting);
         //get the original images, not compressed ones (just in case the thumbnails are, like, full-size & they want quality)
         container.ComposeExportedValue <Action <int, int, HtmlDom, Action <Image>, Action <Exception> > >(GetThumbnailAsync);
         container.SatisfyImportsOnce(this);
         return(_getExtensionMenuItems == null ? new List <ToolStripItem>() : _getExtensionMenuItems());
     }
     else
     {
         return(new List <ToolStripMenuItem>());
     }
 }
Example #24
0
        //protected override Type GetControllerType(RequestContext requestContext, string controllerName)
        //{
        //    var controllerType = base.GetControllerType(requestContext, controllerName);

        //    if (controllerType == null)
        //    {
        //        var controller = _container.GetExports<IController, IControllerMetaData>().SingleOrDefault(x => x.Metadata.ControllerName == controllerName).Value;

        //        if (controller != null)
        //        {
        //            return controller.GetType();
        //        }
        //    }
        //    return controllerType;
        //}

        protected override IController GetControllerInstance(RequestContext context, Type controllerType)
        {
            IController result = null;


            if (!AzRBootstrap.IsIntialized)
            {
                AzRBootstrap.Intialize();
                ControllerBuilder.Current.SetControllerFactory(new AzRControllerFactory(AzRBootstrap.Container));
            }
            if (controllerType == null)
            {
                return(null);
            }
            //if (controllerType == null)
            //{
            //    return base.GetControllerInstance(context, controllerType);
            //    // return null;
            //}

            var export = _container.GetExports(typeof(IAzRController), null, controllerType.FullName).SingleOrDefault(x => x.Value.GetType() == controllerType);

            if (null != export)
            {
                result = export.Value as IController;
            }

            if (null != result)
            {
                _container.SatisfyImportsOnce(result);
            }

            return(result);
        }
        private void Compose()
        {
            AssemblyCatalog      catalog   = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
            CompositionContainer container = new CompositionContainer(catalog);

            container.SatisfyImportsOnce(this);
        }
Example #26
0
        private void Compose()
        {
            var catalog   = new DirectoryCatalog(".", "*.dll");
            var container = new CompositionContainer(catalog);

            container.SatisfyImportsOnce(this);
        }
        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);
        }
Example #28
0
        public ExampleApplication(int width = 512, int height = 512, double updateRate = 60)
        {
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(ExampleApplication).Assembly));
            _container = new CompositionContainer(catalog);
            try
            {
                _container.SatisfyImportsOnce(this);
            }
            catch (CompositionException e)
            {
                Console.WriteLine(e.ToString());
            }

            gameWindow = new GameWindow(width, height);
            gameWindow.TargetUpdateFrequency = updateRate;
            gameWindow.TargetRenderFrequency = updateRate;
            gameWindow.VSync = VSyncMode.On;
            //register callback for resizing of window
            gameWindow.Resize += GameWindow_Resize;
            //register callback for keyboard
            gameWindow.KeyDown += GameWindow_KeyDown;
            gameWindow.KeyDown += (sender, e) => { if (Key.Escape == e.Key)
                                                   {
                                                       gameWindow.Exit();
                                                   }
            };
            ResourceManager = resourceProvider as ResourceManager;
        }
Example #29
0
        public static void Init(object attributedPart)
        {
            if (mefContainer != null)
            {
                return;
            }

            AggregateCatalog partsCatalog = new AggregateCatalog();

            //TODO: replace the following code to load plugins from a subfolder, remove specific plugin references from application project and set plugin projects to copy their DLL to a "Plugins" subfolder under the folder where the executable of the app is built
            string[] assemblies = new string[]
            {
                "SpeechLib.Synthesis.dll",
                "SpeechLib.Recognition.dll",
                "SpeechLib.Recognition.KinectV1.dll"
            };

            foreach (string s in assemblies)
            {
                partsCatalog.Catalogs.Add(new AssemblyCatalog(s));
            }

            mefContainer = new CompositionContainer(partsCatalog);
            mefContainer.SatisfyImportsOnce(attributedPart);
            //CompositionInitializer.SatisfyImports(attributedPart);
        }
Example #30
0
        public void DoLoad()
        {
            //Katalógusokat tároló katalógus
            var catalog = new AggregateCatalog();

            //Futtató szerelvényből típusok keresése, amik Export atribútummal meg vannak jelölve
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            //Adott mappából szerelvények betöltése és az Export atribútummal megjelölt típusok betöltése
            catalog.Catalogs.Add(new DirectoryCatalog(Environment.CurrentDirectory));
            //Kompozíciós konténer létrehozása. A betöltés itt valósul meg.
            CompositionContainer container = new CompositionContainer(catalog);

            //IHost elérhetőségének tesztelése.
            _host = container.GetExportedValue <IHost>();

            if (_host == null)
            {
                Console.WriteLine("Nincs host. Valami gond van");
                Environment.Exit(-1);
            }

            //A modulok betöltése
            container.ComposeParts(this);
            //A modulok számára az IHost függőség kielégítése
            container.SatisfyImportsOnce(this);
        }
        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);
        }
        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);
        }