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;
      }
    }
 public ModuleService()
 {
     var path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
     var catalog = new DirectoryCatalog(path);
     _container = new CompositionContainer(catalog);
     _container.SatisfyImportsOnce(this);
 }
Пример #3
0
        protected override void OnStartup( StartupEventArgs e )
        {
            base.OnStartup( e );

            new UnhandledExceptionHook( this );

            Application.Current.Exit += OnShutdown;

            var catalog = new AssemblyCatalog( GetType().Assembly );
            myContainer = new CompositionContainer( catalog, CompositionOptions.DisableSilentRejection );

            myContainer.Compose( new CompositionBatch() );

            var shell = myContainer.GetExportedValue<Shell>();

            myContainer.SatisfyImportsOnce( shell.myDesigner );

            ( ( Shell )MainWindow ).myProperties.DataContext = shell.myDesigner.SelectionService;

            Application.Current.MainWindow = shell;
            Application.Current.MainWindow.Show();

            var args = Environment.GetCommandLineArgs();
            if( args.Length == 2 )
            {
                shell.myDesigner.Open( args[ 1 ] );
            }
        }
Пример #4
0
		void LoadPlugins() {
			try{
				var pluginsPath = Utils.MapPath("~/plugins");
				if (!Directory.Exists(pluginsPath)) {
					plugins = Enumerable.Empty<IPlugin>();
					return;
				}
				var catalog = new DirectoryCatalog(pluginsPath);
				var container = new CompositionContainer(catalog);
				container.SatisfyImportsOnce(this);
			} catch (Exception err) {
				//swallow error
				log.WriteError(String.Format("error during loading plugins: {0}", err.Message));
				dbg.Break();
				plugins = Enumerable.Empty<IPlugin>();
			}
			foreach (var p in plugins) {
				try {
					p.Init();
				} catch (Exception err) {
					//swallow error
					log.WriteError(String.Format("error during plugin initialization: {0}", err.Message));
					dbg.Break();
				}
			}
		}
Пример #5
0
        public void ComposeWithTypesExportedFromPythonAndCSharp(
            object compositionTarget,
            string scriptsToImport,
            params Type[] typesToImport)
        {
            ScriptSource script;
            var engine = Python.CreateEngine();
            using (var scriptStream = GetType().Assembly.
                GetManifestResourceStream(GetType(), scriptsToImport))
            using (var scriptText = new StreamReader(scriptStream))
            {
                script = engine.CreateScriptSourceFromString(scriptText.ReadToEnd());
            }

            var typeExtractor = new ExtractTypesFromScript(engine);
            var exports = typeExtractor.GetPartsFromScript(script, typesToImport).ToList();

            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

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

            container.SatisfyImportsOnce(compositionTarget);
        }
Пример #6
0
        /// <summary>
        /// MEF Bootstrap (MEF comes from System.ComponentModel.Composition in the GAC).
        /// <para>This will return a class containing all the application's aggregate roots.</para>
        /// </summary>
        public static ComposedDemoProgram Configure(params string[] pluginDirectories)
        {
            var catalogues = 
                pluginDirectories.Select<string, ComposablePartCatalog>(d=>new DirectoryCatalog(d)).
                Concat(new []{new AssemblyCatalog(Assembly.GetExecutingAssembly())}).ToList();

            var catalog = new AggregateCatalog(catalogues);
            try
            {
                var container = new CompositionContainer(catalog);

                var composedProgram = new ComposedDemoProgram();
                container.SatisfyImportsOnce(composedProgram);

                return composedProgram;
            }
            finally
            {
                catalog.Dispose();
                foreach (var cat in catalogues)
                {
                    cat.Dispose();
                }
            }
        }
 private void Compose()
 {
     var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
     var catalog = new DirectoryCatalog(path);
     _container = new CompositionContainer(catalog);
     _container.SatisfyImportsOnce(this);
 }
Пример #8
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));
            }
        }
Пример #9
0
    public static IContainer Initialize(CompositionContainer container, bool resetSingleton)
    {
      Bootstrap bootStrap;

      lock (_lockObject)
      { //  only work on bootstrap instance in one thread at a time
        if (resetSingleton || _instance == null)
        { //  create and MEF initialize the bootstrap object
          bootStrap = new Bootstrap();
          container.SatisfyImportsOnce(bootStrap);
          //  store in singleton
          _instance = bootStrap;
        }
        //  use current instance
        bootStrap = _instance;
      }

      //  now initialize autofac
      ContainerBuilder builder = new ContainerBuilder();
      
      //  add support for implicit collections
      builder.RegisterModule(new Autofac.Modules.ImplicitCollectionSupportModule());
      
      //  add all MEF-ed modules
      foreach (Module module in bootStrap.Modules)
        builder.RegisterModule(module);

      //  create the container
      return builder.Build();
    }
Пример #10
0
 protected virtual void Application_Start(Object sender, EventArgs e)
 {
     DirectoryCatalog dirCatalog = new DirectoryCatalog(Server.MapPath("bin"),"*.dll");
     AssemblyCatalog asCatalog = new AssemblyCatalog(this.GetType().Assembly);
     AggregateCatalog catalog = new AggregateCatalog(dirCatalog,asCatalog);
     CompositionContainer container = new CompositionContainer(catalog);
     container.SatisfyImportsOnce(this);
 }
Пример #11
0
 private void InitializeMEF()
 {
     CompositionContainer container = new CompositionContainer(new AssemblyCatalog(GetType().Assembly));
     CompositionBatch batch = new CompositionBatch();
     batch.AddExportedValue(container);
     container.Compose(batch);
     container.SatisfyImportsOnce(this);
 }
Пример #12
0
 public DataManService()
 {
   var catalog = new AggregateCatalog();
   catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
   catalog.Catalogs.Add(new AssemblyCatalog(typeof(IData).Assembly));
   _container = new CompositionContainer(catalog);
   _container.SatisfyImportsOnce(this);
   _data = Data;
 }
 public void SatisfyImportsOnce(ComposablePart part)
 {
     Requires.NotNull(part, nameof(part));
     if (_compositionContainer == null)
     {
         throw new Exception(SR.Diagnostic_InternalExceptionMessage);
     }
     _compositionContainer.SatisfyImportsOnce(part);
 }
        public void Setup()
        {
            // See notes in TrailTest class about wiring up the repository
            DirectoryCatalog repositoryCatalog = new DirectoryCatalog(@".\PlugIns");
            _repositoryFactory = new RepositoryFactory();

            // Now, set up the MEF container and use it to hydrate the _repositoryFactory object
            _container = new CompositionContainer(repositoryCatalog);
            _container.SatisfyImportsOnce(_repositoryFactory);
        }
Пример #15
0
            /// <summary>
            /// Translate an expression.
            /// </summary>
            /// <param name="expr"></param>
            /// <param name="cc"></param>
            /// <returns></returns>
            public static Expression Translate(Expression expr, IGeneratedQueryCode gc, ICodeContext cc, CompositionContainer container)
            {
                var tr = new ResolveToExpression() { CodeContext = cc, GeneratedCode = gc, MEFContainer = container };
                if (container != null)
                {
                    container.SatisfyImportsOnce(tr);
                }

                return tr.Visit(expr);
            }
Пример #16
0
        public Tester() {
            InitializeComponent();

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(DirectInputProvider).Assembly));

            var container = new CompositionContainer(catalog);
            container.SatisfyImportsOnce(this);

            this.inputProviderList.Items.AddRange(inputProviders.Select((ip) => ip.Name).ToArray());
        }
        public void Initialize()
        {
            if (Plugins == null)
            {
                // MEF loading of available plug-ins
                var catalog = new DirectoryCatalog(".", "UUM.Plugin.*.dll");
                var container = new CompositionContainer(catalog);

                container.SatisfyImportsOnce(this);
            }
        }
Пример #18
0
        /// <summary>
        /// Initializes new instance with specified path used for loading processing nodes, and number of worker threads
        /// </summary>
        /// <param name="path"></param>
        public AlgoGrid(string path, int workerThreadCount)
        {
            m_dispatcher = new Dispatcher(workerThreadCount, "ThreadPool");
            m_dispatcherQueue = new DispatcherQueue("Queue", m_dispatcher);
            m_queue = new Port<IBaseItem>();
            ITask task = Arbiter.Receive(true, m_queue, InnerHandle);
            Arbiter.Activate(m_dispatcherQueue, task);

            DirectoryCatalog catalog = new DirectoryCatalog(path);
            CompositionContainer container = new CompositionContainer(catalog);
            container.SatisfyImportsOnce(this);
        }
        public void Setup()
        {
            // Options for setting up dependency injection using MEF:
            // e.g. see http://msdn.microsoft.com/en-us/magazine/ee291628.aspx
            //      and http://buksbaum.us/2011/08/22/gentle-introduction-to-mefpart-two/

            // 1. Use the TypeCatalog and explicitly reference the types - this requires a reference to the injected type,
            // which kind of defeats the purpose of having it as a pluggable component
            //TypeCatalog repositoryCatalog = new TypeCatalog(typeof(IRepository), typeof(EFRepository)),typeof(NHibernateRepository))

            // 2. Use the Directory Catalog and point to the folder in which our executable is.
            //      (which in this case is likely to be C:\Projects\Personal\Trails2012\Trails2012.Tests\bin\Debug)
            // NOTE: we do not (indeed, we should not) have an explicit reference to the assembly containing our plugabble repository
            // NOTE:         (i.e. the one that uses Entity Framework - "Trails2012.DataAccess.EF")
            // NOTE: so a version of the assembly file is _not_ copied into the executing folder automatically whenever this ("Trails2102.Test") assembly is built.
            // NOTE: We need to explicitly place a _current_copy of the Trails2012.DataAccess.EF.dll file into our executing folder,
            // NOTE: as well as all of its dependencies
            DirectoryCatalog repositoryCatalog = new DirectoryCatalog(@".\PlugIns");

            // 3. Use the Directory Catalog and point to the folder which contains our pluggable component
            //      (which in this case is likely to be C:\Projects\Personal\Trails2012\Trails2012.DataAccess.EF\bin\Debug)
            //Assembly executingAssembly = Assembly.GetExecutingAssembly();
            //bool found = executingAssembly.GetCustomAttributes(typeof(DebuggableAttribute), false).Length > 0;
            //string configString = (found ? "debug" : "release");
            //DirectoryCatalog repositoryCatalog = new DirectoryCatalog(@"..\..\..\Trails2012.DataAccess.EF\bin\" + configString);

            // 4. Use an AssemblyCatalog??? Not sure this works - it would need the pluggable component to be part of the assembly
            //AssemblyCatalog repositoryCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            // Of course, we can use all/any of the above and combine the using an AggregateCatalog (http://mef.codeplex.com/wikipage?title=Using%20Catalogs)
            // e.g. var catalog = new AggregateCatalog(
            //                  new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()),
            //                  new DirectoryCatalog(@".\Extensions"));

            // 5. Skip dependency injection and inject the repository explicitly (just for this Test assembly).
            // However, to do that we need to get a reference to the pluggable repository, in which case, we would need a reference in this test assembly
            // Use an internal constructor on the RepositoryFactory class and set the InternalsVisibleTo attribute of the DataAccess assembly to include this Test assembly
            //EFRepository repository = new EFRepository();
            //_repositoryFactory = new RepositoryFactory(repository);
            // or
            //_repositoryFactory = new RepositoryFactory();
            // _repositoryFactory.Repository = repository;

            _repositoryFactory = new RepositoryFactory();

            // Now, set up the MEF container and use it to hydrate the _repositoryFactory object
            _container = new CompositionContainer(repositoryCatalog);
            _container.SatisfyImportsOnce(_repositoryFactory);
        }
Пример #20
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            if (!Directory.Exists(extensionsPath))
                return;

            var container = new CompositionContainer(
                new DirectoryCatalog(extensionsPath)
                );

            container.SatisfyImportsOnce(this);
            foreach (var export in Extensions)
            {
                var extension = export.Value;
                var controller = extension as RoutableFunnelWebExtension;
                var requiresScripts = extension as IRequireDatabaseScripts;

                if (requiresScripts != null)
                {
                    var ex = new ScriptedExtension(
                        requiresScripts.SourceIdentifier,
                        extension.GetType().Assembly,
                        new EmbeddedScriptProvider(
                            extension.GetType().Assembly,
                            script => script.EndsWith(".sql")));

                    builder.RegisterInstance(ex);
                }

                if (controller != null)
                {
                    controller.Routes = routes;
                    controller.Initialize(builder);
                    controller.RegisterControllers(builder);
                }
                else
                {
                    extension.Initialize(builder);
                }
                builder.RegisterInstance(export.Metadata).As<IFunnelWebExtensionMetaData>();
            }
        }
        /// <summary>
        /// Parse an array expression, and turn it into a loop. Use indexName as the loop variable. Bomb if we can't do it. If you hand in null we will make up our own.
        /// </summary>
        /// <param name="query">The query that this loop is associated with.</param>
        /// <param name="expr">The expression that evaluates to an array.</param>
        /// <param name="gc"></param>
        /// <param name="cc"></param>
        /// <param name="container"></param>
        public static IVariableScopeHolder ParseArrayExpression(IQuerySource query, Expression expr, IGeneratedQueryCode gc, ICodeContext cc, CompositionContainer container)
        {
            if (_parser == null)
            {
                _parser = new ArrayExpressionParser();
                container.SatisfyImportsOnce(_parser);
            }

            var result = _parser.GetIArrayInfo(expr, gc, cc, container);

            if (result == null)
                throw new InvalidOperationException($"Can't figure out how to loop over this array: '{expr.ToString()}' (expression: '{expr.NodeType}', type: '{expr.Type.FullyQualifiedName()}')");

            //
            // Turn it into code - any code that we need.
            //

            return result.CodeLoopOverArrayInfo(query, gc, cc, container);
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            // Construct our main window
            // We create the view model here so we can tell MEF to use this instance of it, rather than create its own
            var mainWindow = new MainWindow();
            var mainViewModel = new MainViewModel();
            var mainView = new MainView(mainViewModel);
            mainWindow.Content = mainView;

            // Creat a directory (plugins) and assembly catalog (exports)
            var catalog = new DirectoryCatalog(".");
            var asmCatalog = new AssemblyCatalog(this.GetType().Assembly);

            CompositionContainer container = new CompositionContainer(new AggregateCatalog(catalog, asmCatalog));

            // Register our current instance of MainViewModel with the container
            // If we don't do this then MEF will create its own
            //
            // We only need to do this because our view and viewmodel is already constructed.
            container.ComposeExportedValue<IMessageService>(mainViewModel);

            // Wireup our plugins, which in turn wires up their imports
            container.SatisfyImportsOnce(this);

            // We can now work with the metadata and only initialise the plugins we want
            // The plugin won't even be constructed if we choose not to access "plugin.Value"
            if (Plugins != null)
            {
                foreach (var plugin in Plugins)
                {
                    // Don't load anything named "Plugin2" - we could use this for allowing users
                    // to specify plugins to load/not load at a later date.
                    //
                    // Plugin2's Main class is never constructed
                    if (plugin.Metadata.Name != "Plugin2")
                        plugin.Value.Initialise();
                }
            }

            mainWindow.Show();
        }
Пример #23
0
        public void Compose(object target, ILogger logger)
        {
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var owningAssemblyCatalog = new AssemblyCatalog(_callingAssembly);

            //load any plugins from the plugins folder
            var pluginsCatalog = new DirectoryCatalog("Plugins", "*.dll");

            var catalog = new AggregateCatalog(assemblyCatalog, pluginsCatalog, owningAssemblyCatalog);
            var container = new CompositionContainer(catalog);
            container.SatisfyImportsOnce(target);

            logger.Write("Handlers loaded:");
            logger.WriteIndented($"{Path.GetFileName(Assembly.GetExecutingAssembly().Location)} ({FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion})");
            logger.WriteIndented($"{Path.GetFileName(_callingAssembly.Location)} ({FileVersionInfo.GetVersionInfo(_callingAssembly.Location).FileVersion})");

            logger.Write("Plugins loaded:");
            foreach (var file in pluginsCatalog.LoadedFiles)
            {
                logger.WriteIndented($"{Path.GetFileName(file).ToLower()} ({FileVersionInfo.GetVersionInfo(file).FileVersion})");
            }
        }
        //[TestInitialize]
        public void SetupRepositoryUsingMEF()
        {
            // It would be nice to specify a Moq wrapper of an IRepository
            // and register it with MEF
            // so that it gets injected into the RepositoryFactory
            TypeCatalog repositoryCatalog = new TypeCatalog(typeof(IRepository), typeof(Mock<IRepository>));
            _repositoryFactory = new RepositoryFactory();
            _container = new CompositionContainer(repositoryCatalog);
            _container.SatisfyImportsOnce(_repositoryFactory);

            // However this does not work.
            // It causes the following MEF error: 1) No valid exports were found that match the constraint '((exportDefinition.ContractName == "Trails2012.DataAccess.IRepository") AndAlso (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") AndAlso "Trails2012.DataAccess.IRepository".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))', invalid exports may have been rejected.
            //      because the Moq wrapper is not decorated with the MEF attribute:
            // [Export(typeof(IRepository))]
            // Hmm...I do not like that MEF requires you to decorate classes with attributes -
            //      other IOC containers do not do that.

            // Still, no biggie. RepositoryFactory is a test-specific artifact anyway.
            // Instead, we will not use MEF, but inject the IRepository manually.
            // I have set the controllers up with constructors which MEF uses,
            //      and which take IRepository as parameter, so we can just use those constructors.
        }
Пример #25
0
        private void SatisfyImports()
        {
            var assemblyCatalogs = new List<AssemblyCatalog>();

            var directory = Path.GetDirectoryName(typeof(ImportsModule).Assembly.Location);

            foreach (var assemblyFile in Directory.EnumerateFiles(directory, "*.dll"))
            {
                try
                {
                    var catalog = new AssemblyCatalog(Assembly.LoadFile(assemblyFile));
                    catalog.Parts.ToArray();
                    assemblyCatalogs.Add(catalog);
                }
                catch
                {
                }
            }

            var aggregateCatalog = new AggregateCatalog(assemblyCatalogs);
            var container = new CompositionContainer(aggregateCatalog);

            container.SatisfyImportsOnce(this);
        }
Пример #26
0
 void ICompositionService.SatisfyImportsOnce(ComposablePart part)
 {
     _innerContainer.SatisfyImportsOnce(part);
 }
Пример #27
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", _collectionSettings.Language1Iso639Code);
         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>();
     }
 }
        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"));
        }
Пример #29
0
 public void SatisfyImportsOnce(ComposablePart part)
 {
     Requires.NotNull(part, nameof(part));
     Assumes.NotNull(_compositionContainer);
     _compositionContainer.SatisfyImportsOnce(part);
 }
Пример #30
0
        protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);

            TaskScheduler.UnobservedTaskException += (sender, args) => HandleException(args.Exception);

            container = new CompositionContainer(new AssemblyCatalog(typeof (App).Assembly));

            var activationArguments = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;
            var activationData = activationArguments != null ? activationArguments.ActivationData : null;

            var filePath = (activationData ?? e.Args)
                .Select(x => x.Replace("file:///", string.Empty))
                .FirstOrDefault();

            this.ShutdownMode = ShutdownMode.OnExplicitShutdown;

            if (string.IsNullOrEmpty(filePath)) {
                var view = new SelectSourceView();

                container.SatisfyImportsOnce(view.ViewModel);

                if (view.ShowDialog() == true)
                    SourceInfo = view.ViewModel.Source;
            } else {
                var factory = new FileLogSourceFactory();
                SourceInfo = factory.Create(SelectFormat, filePath);
            }

            if (SourceInfo == null) {
                this.Shutdown();
                return;
            }

            this.ShutdownMode = ShutdownMode.OnLastWindowClose;

            this.MainWindow = new ShellView();
            this.MainWindow.Closed += (sender, args) => SourceInfo.Source.Dispose();
            this.MainWindow.Show();
        }
        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=4.0.0.0, Culture=neutral, PublicKeyToken=null", moduleInfo.ModuleType);
            Assert.IsTrue(wasInit);
        }
Пример #32
0
        private void LoadPlugins()
        {
            logger.Info("load plugins");

            var folders = new HashSet<string>();

            var catalog = new AggregateCatalog(new ApplicationCatalog());

            var spDir = new DirectoryInfo(AppSettings.ShadowedPluginsFullPath);

            foreach (var dir in spDir.GetDirectories())
            {
                var subCatalog = new DirectoryCatalog(dir.FullName);
                catalog.Catalogs.Add(subCatalog);

                folders.Add(dir.FullName);
            }

            AppDomain.CurrentDomain.SetupInformation.PrivateBinPath = string.Join(";", folders);

            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);
        }