Exemple #1
0
        /// <summary>
        /// Loads all CustomClasses from CustomClasses folder
        /// </summary>
        public void Refresh()
        {
            if (_customClasses != null)
            {
                foreach (var x in _customClasses)
                {
                    $"CustomClasses: Disposing CC {x.Name}".Log(LogFiles.InjectedLog, true);
                    x.Dispose();
                }
            }
            if (_catalog != null)
            {
                $"CustomClasses: Disposing old catalog".Log(LogFiles.InjectedLog, true);
                _catalog.Catalogs.Clear();
                _catalog?.Dispose();
            }
            _catalog = new AggregateCatalog();
            _customClasses?.Clear();
            _container?.Dispose();
            Action <string> load = item =>
            {
                if (!item.EndsWith(".dll"))
                {
                    return;
                }
                $"CustomClasses: Noting down {item} as possible CustomClass".Log(LogFiles.InjectedLog, true);
                var dir = Path.GetDirectoryName(item);
                DependencyLoader.SetPluginPath(dir);
                var assembly = Assembly.Load(File.ReadAllBytes(item));
                _catalog.Catalogs.Add(new AssemblyCatalog(assembly));
            };

            foreach (var path in Directory.EnumerateDirectories(Paths.CustomClasses, "*", SearchOption.TopDirectoryOnly))
            {
                foreach (var item in Directory.GetFiles(path))
                {
                    load(item);
                }
            }
            foreach (var item in Directory.GetFiles(Paths.CustomClasses))
            {
                load(item);
            }
            _container = new CompositionContainer(_catalog);
            $"CustomClasses: Composing catalogs".Log(LogFiles.InjectedLog, true);
            _container.ComposeParts(this);
            var tmpList = new HashSet <string>();

            foreach (var x in _customClasses)
            {
                var name = x.Name.ToLower();
                $"CustomClasses: Loaded {name} botbase".Log(LogFiles.InjectedLog, true);
                if (tmpList.Contains(name))
                {
                    App.QuitWithMessage(
                        $"Name of CustomClasses must be unique however there are two or more bases with name {x.Name}");
                }
                tmpList.Add(name);
            }
        }
        /// <summary>
        /// Gets provider repository.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>
        /// Provider repository.
        /// </returns>
        private CompositionContainer GetCompositionContainer(IInput input)
        {
            CompositionContainer container;

            using (var catalog = new AggregateCatalog())
            {
                var adaptersDirectory = AssemblyHelper.GetExecutingAssemblyDirectory();
                var item = new SafeDirectoryCatalog(adaptersDirectory);
                catalog.Catalogs.Add(item);

                CompositionContainer tempContainer = null;
                try
                {
                    tempContainer = new CompositionContainer(catalog);
                    var ctorAdapterParameters = new ProviderParameters {
                        Data = input.Data
                    };
                    tempContainer.ComposeExportedValue(ctorAdapterParameters);
                    tempContainer.ComposeParts(this);
                    container     = tempContainer;
                    tempContainer = null;
                }
                catch
                {
                    throw;
                }
                finally
                {
                    tempContainer?.Dispose();
                }
            }

            return(container);
        }
Exemple #3
0
        /// <summary>
        ///     The events_ on close.
        /// </summary>
        /// <param name="sender">
        ///     The sender.
        /// </param>
        /// <param name="e">
        ///     The e.
        /// </param>
        private void Events_OnClose(object sender, EventArgs e)
        {
            if (!this.initialized)
            {
                return;
            }

            this.initialized = false;
            Events.OnClose  -= this.Events_OnClose;

            this.AbilityDataCollector?.Value?.OnClose();

            this.MainMenuManager?.Value?.OnClose();

            this.AbilityUnitManager?.Value?.OnClose();

            this.AbilityFactory?.Value?.OnClose();

            this.AbilityModuleManager?.Value?.OnClose();

            if (this.AbilityServices != null && this.AbilityServices.Any())
            {
                foreach (var abilityService in this.AbilityServices)
                {
                    abilityService?.Value?.OnClose();
                }
            }

            container?.Dispose();
            catalog?.Dispose();
        }
Exemple #4
0
 private static void Dispose(bool disposing)
 {
     if (disposing)
     {
         CompositionContainer?.Dispose();
     }
 }
        public void Dispose()
        {
            _conceptsView.DataContext = null;
            RegionManager.Regions.Remove("ConceptsRegion");

            _localContainer?.Dispose();
        }
Exemple #6
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <remarks>
        /// <para>
        /// <note type="important">
        /// <para>
        /// This method must be called, or the application domain that is created to interrogate assembly types will live until the end of the application. This could lead to memory bloat or worse.
        /// </para>
        /// <para>
        /// Because the application domain is unloaded on a separate thread, it may deadlock with the finalizer thread and thus we cannot count on the finalizer to clean evict the stale app domain on our
        /// behalf.
        /// </para>
        /// </note>
        /// </para>
        /// </remarks>
        public void Dispose()
        {
            Log.Print("Unloading MEF plugin container and catalogs.", LoggingLevel.Intermediate);

            _container?.Dispose();
            _container = null;
            _rootCatalog?.Dispose();
            _rootCatalog = null;
        }
        private void FilterActiveBundles()
        {
            container?.Dispose();
            container = null;

            var catalog = GetUnfilteredCatalogs(Catalog.Catalogs);

            Catalog = new AggregateCatalog(new List <ComposablePartCatalog> {
                new BundlesFilteredCatalog(catalog, Core.ActiveBundles.ToArray())
            });
        }
Exemple #8
0
 protected override void OnExit(ExitEventArgs e)
 {
     foreach (var moduleController in moduleControllers.Reverse())
     {
         moduleController.Shutdown();
     }
     container?.Dispose();
     catalog?.Dispose();
     Log.App.Info("{0} closed", ApplicationInfo.ProductName);
     base.OnExit(e);
 }
        private bool disposedValue = false; // 重複する呼び出しを検出するには

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    DisposablePlugins.ForEach(plugin => plugin.Dispose());
                    container?.Dispose();
                }
                disposedValue = true;
            }
        }
 public void Dispose()
 {
     foreach (var plugin in Plugins)
     {
         try {
             plugin?.Value?.Dispose();
         }
         catch (Exception e) {
             Console.WriteLine(e);
         }
     }
     _container?.Dispose();
 }
Exemple #11
0
        private bool disposedValue; // To detect redundant calls

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // NOTE: dispose managed state (managed objects).
                    _container?.Dispose();
                }

                // NOTE: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // NOTE: set large fields to null.

                disposedValue = true;
            }
        }
Exemple #12
0
        public void Execute()
        {
            //
            // カタログ構築.
            //  AggregateCatalogは、複数のCatalogを一つにまとめる役割を持つ。
            //
            var catalog = new AggregateCatalog();

            // AssemblyCatalogを利用して、自分自身のアセンブリをカタログに追加.
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(MEFSamples01).Assembly));

            //
            // コンテナを構築.
            //
            _container = new CompositionContainer(catalog);
            try
            {
                // 合成実行.
                _container.ComposeParts(this);

                // 実行.
                foreach (var lazyObj in _exporters)
                {
                    //
                    // メタデータを調べ、合致したもののみを実行する.
                    // Lazy<T, TMetadata>.Valueを呼ばない限りインスタンスは作成されない。
                    //
                    if (lazyObj.Metadata.Symbol == "SECOND")
                    {
                        Output.WriteLine(lazyObj.Value.Name);
                    }
                }
            }
            catch (CompositionException ex)
            {
                // 合成に失敗した場合.
                Output.WriteLine(ex.ToString());
            }

            if (_container != null)
            {
                _container.Dispose();
            }
        }
        public void CanBeCollectedAfterDispose()
        {
            AggregateExportProvider exportProvider = new AggregateExportProvider();
            var catalog   = new AggregateCatalog(CatalogFactory.CreateDefaultAttributed());
            var container = new CompositionContainer(catalog, exportProvider);

            WeakReference weakContainer = new WeakReference(container);

            container.Dispose();
            container = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Assert.False(weakContainer.IsAlive);

            GC.KeepAlive(exportProvider);
            GC.KeepAlive(catalog);
        }
Exemple #14
0
        static void Main(string[] args)
        {
            AssemblyCatalog      catalog   = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            CompositionContainer container = new CompositionContainer(catalog);

            for (int i = 0; i < 10; i++)
            {
                var tmp = container.GetExportedValue <DisposablePart>();
                //releasing the instance by setting it to null
                tmp = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            container.Dispose();

            Console.ReadKey();
        }
Exemple #15
0
        /// <summary>
        /// Gets writers repository.
        /// </summary>
        /// <param name="settings">Writer cache settings.</param>
        /// <returns>
        /// Writer repository.
        /// </returns>
        private CompositionContainer GetCompositionContainer(WritersCacheSettings settings)
        {
            CompositionContainer container;

            using (var catalog = new AggregateCatalog())
            {
                foreach (var path in settings.Items)
                {
                    var item = new SafeDirectoryCatalog(path);
                    catalog.Catalogs.Add(item);
                    using (var writerWatcher = GetWriterWatcher(path))
                    {
                        var addWatcher = _watchers.All(watch => watch.Path != path);
                        if (addWatcher)
                        {
                            _watchers.Add(writerWatcher);
                        }
                    }
                }

                CompositionContainer tempContainer = null;
                try
                {
                    tempContainer = new CompositionContainer(catalog);
                    try
                    {
                        tempContainer.ComposeParts(this);
                        container     = tempContainer;
                        tempContainer = null;
                    }
                    catch (CompositionException)
                    {
                        throw;
                    }
                }
                finally
                {
                    tempContainer?.Dispose();
                }
            }

            return(container);
        }
        /// <summary>
        ///     The events_ on close.
        /// </summary>
        /// <param name="sender">
        ///     The sender.
        /// </param>
        /// <param name="e">
        ///     The e.
        /// </param>
        private void Events_OnClose(object sender, EventArgs e)
        {
            if (!this.initialized)
            {
                return;
            }

            this.initialized = false;
            this.MainMenuManager.Value?.OnClose();
            this.AbilityUnitManager.Value?.OnClose();

            foreach (var abilityService in this.AbilityServices)
            {
                abilityService.Value?.OnClose();
            }

            container?.Dispose();
            catalog?.Dispose();
        }
Exemple #17
0
        private void Application_Exit(object sender, ExitEventArgs e)
        {
            if (_container != null)
            {
                _container.Dispose();
            }

            // Try to save, if there's an IO error, just ignore it here, nothing we can do
            try
            {
                Settings.Default.Save();
            }
            catch
            {
            }

            DiagnosticsClient.TrackEvent("AppExit");

            DiagnosticsClient.OnExit();
        }
        private void Application_Exit(object sender, ExitEventArgs e)
        {
            if (_container != null)
            {
                _container.Dispose();
            }

            // IMPORTANT: Call this after calling _container.Dispose(). Some exports relies on Dispose()
            // being called to save settings values.
            Settings.Default.IsFirstTimeAfterMigrate = false;

            // Try to save, if there's an IO error, just ignore it here, nothing we can do
            try
            {
                Settings.Default.Save();
            }
            catch
            {
            }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            //Setting up parent Catalog
            TypeCatalog parentCatalog = new TypeCatalog(typeof(Logger));

            //Since logging is something used throughout the application, it makes sense to have it in the parent container.
            parentContainer = new CompositionContainer(parentCatalog);

            PerformWork();

            //Since we know that the child container is disposed, let's see what happens to the parentContainer.
            var logger = parentContainer.GetExportedValue <Logger>();

            logger.Log("Logger still works!");

            //Then we will dispose the parent container.
            parentContainer.Dispose();

            Console.ReadKey();
        }
Exemple #20
0
        private void Compose()
        {
            _logger.Info("Adapter Service is looking for a plugin");
            CompositionContainer container = null;

            try
            {
                string codebase = AppDomain.CurrentDomain.BaseDirectory;

                var pluginAssembly = ConfigurationManager.AppSettings["pluginAssembly"];
                var catalog        = new SafeDirectoryCatalog(codebase, pluginAssembly);
                container = new CompositionContainer(catalog);
                container.ComposeParts(this);
                PlatformConnectorInstance = PlatformConnector;
            }
            catch (CompositionException ex)
            {
                foreach (var error in ex.Errors)
                {
                    _logger.Fatal("Error when loading plugin", error.Exception);
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                foreach (var error in ex.LoaderExceptions)
                {
                    _logger.Fatal("Error when searching for plugin", error);
                }
            }
            catch (Exception ex)
            {
                _logger.Fatal("Error when loading plugin", ex);
            }
            finally
            {
                if (container != null)
                {
                    container.Dispose();
                }
            }
        }
Exemple #21
0
        public void PartAddedTwice_AppearsTwice()
        {
            //  You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on
            var container  = new CompositionContainer();
            var disposable = new AnyPartDisposable();
            var part       = AttributedModelServices.CreatePart(disposable);
            var batch      = new CompositionBatch();

            batch.AddPart(part);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            var exports = container.GetExports <AnyPartDisposable>();

            Assert.AreEqual(2, exports.Count());

            container.Dispose();
        }
Exemple #22
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing,
        /// or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (catalogExportProvider != null)
            {
                catalogExportProvider.Dispose();
            }

            if (compositionContainer != null)
            {
                compositionContainer.Dispose();
            }

            if (aggregateCatalog != null)
            {
                aggregateCatalog.Dispose();
            }

            compositionContainer = null;
            aggregateCatalog     = null;
            providers            = null;
        }
        internal static Collection <T> GetExportedPlugins <T>(string directory, string searchPattern = "*.dll")
        {
            Collection <T>       plugins   = new Collection <T>();
            DirectoryCatalog     catalog   = new DirectoryCatalog(directory, searchPattern);
            CompositionContainer container = new CompositionContainer(catalog);

            try
            {
                foreach (var plugin in container.GetExportedValues <T>())
                {
                    plugins.Add(plugin);
                }
            }
            finally
            {
                catalog.Dispose();
                container.Dispose();
            }

            return(plugins);
        }
Exemple #24
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            try
            {
                foreach (var plugin in Plugins)
                {
                    plugin.Dispose();
                }

                if (_container != null)
                {
                    _container.Dispose();
                }

                if (_catalog != null)
                {
                    _catalog.Dispose();
                }
            }
            catch (Exception)
            { }
        }
Exemple #25
0
        static void PerformWork()
        {
            //We will use the child container in this method.

            //First we will setup our catalog and pass in TemporaryWorker and ResourceLoader parts
            TypeCatalog childCatalog = new TypeCatalog(typeof(TemporaryWorker), typeof(MemoryIntensiveResourceLoader));

            //In the child container, not only we pass the catalog, but also pass the parentContianer reference.
            //All of the parts that parent container knows about, the child container knows about as well.

            //When the child container composes a part, it will use the parent container to satisfy the imports if necessary.
            CompositionContainer childContainer = new CompositionContainer(childCatalog, parentContainer);


            //Then we will grab the temporary container from the child container and call the DoWork method.
            var worker = childContainer.GetExportedValue <TemporaryWorker>();

            worker.DoWork();

            //When the work is complete, we will dispose of the child container.
            childContainer.Dispose();
        }
        internal IEnumerable <IPreflightPlugin> Get()
        {
            AggregateCatalog catalog = new AggregateCatalog(
                new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"), "*.dll"));

            CompositionContainer container = new CompositionContainer(catalog);

            try
            {
                container.ComposeParts(this);
            }
            catch (CompositionException e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                container.Dispose();
            }

            return(_preflightPlugins);
        }
        /// <summary>
        ///     This method can be used to initialize the global container in the case where the default container doesn't provide
        ///     enough flexibility.
        ///
        ///     If this method is needed it should be called exactly once and as early as possible in the application host.
        /// </summary>
        /// <param name="catalogs">
        ///     An array of <see cref="ComposablePartCatalog"/> that should be used to initialize the
        ///     <see cref="CompositionContainer"/> with.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="catalogs"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///     Either <see cref="Initialize(CompositionContainer)" /> or <see cref="Initialize(ComposablePartCatalog[])" />
        ///     has already been called or someone has already made use of the global container. In either case you need to
        ///		ensure that it  is called only once and that it is called early in the application host startup code.
        /// </exception>
        public static CompositionContainer Initialize(params ComposablePartCatalog[] catalogs)
        {
            AggregateCatalog     aggregateCatalog = new AggregateCatalog(catalogs);
            CompositionContainer container        = new CompositionContainer(aggregateCatalog);

            try
            {
                Initialize(container);
            }
            catch
            {
                container.Dispose();

                // NOTE : this is important, as this prevents the disposal of the catalogs passed as input arguments
                aggregateCatalog.Catalogs.Clear();
                aggregateCatalog.Dispose();

                throw;
            }

            return(container);
        }
Exemple #28
0
        /// <summary>
        /// 组合部件
        /// </summary>
        private void Compose()
        {
            //判断Plugins文件夹是否存在
            if (!Directory.Exists("Plugins"))
            {
                Directory.CreateDirectory("Plugins");
            }

            AggregateCatalog catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new DirectoryCatalog("Plugins"));
            _container = new CompositionContainer(catalog);
            try
            {
                _container.ComposeParts(_pluginsImport);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                _container.Dispose();
            }
        }
        protected override void OnExit(ExitEventArgs e)
        {
            // Shutdown the module controllers in reverse order
            foreach (IModuleController moduleController in moduleControllers.Reverse())
            {
                moduleController.Shutdown();
            }

            // Wait until all registered tasks are finished
            var shellService = container.GetExportedValue <IShellService>();

            Task[] tasksToWait = shellService.TasksToCompleteBeforeShutdown.ToArray();
            while (tasksToWait.Any(t => !t.IsCompleted && !t.IsCanceled && !t.IsFaulted))
            {
                DispatcherHelper.DoEvents();
            }

            // Dispose
            container.Dispose();
            catalog.Dispose();
            base.OnExit(e);
        }
        protected void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (disposed)
                {
                    return;
                }

                if (disposables != null)
                {
                    disposables.Dispose();
                }
                disposables = null;
                if (tempContainer != null)
                {
                    tempContainer.Dispose();
                }
                tempContainer = null;
                disposed      = true;
            }
        }