コード例 #1
1
        public SafeDirectoryCatalog(string path)
        {
            exceptions = new List<Exception>();
            var files = Directory.EnumerateFiles(GetFullPath(path), "*.dll", SearchOption.AllDirectories);

            aggregateCatalog = new AggregateCatalog();

            foreach (var file in files)
            {
                try
                {
                    var assemblyCatalog = new AssemblyCatalog(file);

                    if (assemblyCatalog.Parts.ToList().Count > 0)
                        aggregateCatalog.Catalogs.Add(assemblyCatalog);
                }
                catch (ReflectionTypeLoadException ex)
                {
                    foreach (var exception in ex.LoaderExceptions)
                    {
                        exceptions.Add(exception);
                    }
                }
                catch (Exception ex)
                {
                    exceptions.Add(ex);
                }
            }
        }
コード例 #2
0
        public void LoadPlugins(IEnumerable<ComposablePartCatalog> catalogs = null)
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(GetType().Assembly));

            if (catalogs != null)
            {
                foreach (var additionalCatalog in catalogs)
                {
                    catalog.Catalogs.Add(additionalCatalog);
                }
            }

            //Create the CompositionContainer with the parts in the catalog
            Container = new CompositionContainer(catalog);

            //Fill the imports of this object
            try
            {
                Container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }
        }
コード例 #3
0
ファイル: App.cs プロジェクト: JackFong/FreeRadical
        private bool Compose()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(IMefShapesGame).Assembly));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(DefaultDimensions).Assembly));
            var partCreatorEP = new DynamicInstantiationExportProvider();

            this._container = new CompositionContainer(catalog, partCreatorEP);
            partCreatorEP.SourceProvider = this._container;

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);
            batch.AddExportedValue<ICompositionService>(this._container);
            batch.AddExportedValue<AggregateCatalog>(catalog);

            try
            {
                this._container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                Shutdown(1);
                return false;
            }
            return true;
        }
コード例 #4
0
ファイル: CompositionHelper.cs プロジェクト: nootn/ClinImIm
 internal static CompositionContainer GetContainer()
 {
     var catalog = new AggregateCatalog();
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(IApplicationController).Assembly));
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(ValidationModel).Assembly));
     return new CompositionContainer(catalog);
 }
コード例 #5
0
        public TestHarness(string pluginDirectoryPath, Type pluginAssemblyType, string pluginType)
        {
            var catalog = new AggregateCatalog();
            this._pluginType = pluginType;

            try
            {
                Assembly[] assemblies = new Assembly[]{ Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly(), Assembly.GetEntryAssembly() };
                foreach (Assembly assembly in assemblies)
                {
                    catalog.Catalogs.Add(new AssemblyCatalog(assembly));
                    catalog.Catalogs.Add(new DirectoryCatalog(Path.GetDirectoryName(assembly.Location)));
                }

                if (!Object.ReferenceEquals(pluginAssemblyType, null))
                {
                    catalog.Catalogs.Add(new AssemblyCatalog(pluginAssemblyType.Assembly));
                }

                if (!Object.ReferenceEquals(pluginDirectoryPath, null))
                {
                    if (Directory.Exists(pluginDirectoryPath))
                    {
                        catalog.Catalogs.Add(new DirectoryCatalog(pluginDirectoryPath));
                    }
                }

                this.container = new CompositionContainer(catalog);
                this.container.ComposeParts(this);
            }
            catch (CompositionException cex)
            {
                Console.WriteLine(cex.ToString());
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: Olezhka/Hipbot
        public void DoImport()
        {
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();

            directoryCatalog = new DirectoryCatalog(GetDirectory());
            directoryCatalog.Changing += directoryCatalog_Changing;
            directoryCatalog.Changed += directoryCatalog_Changed;

            //Adds all the parts found in all assemblies in 
            //the same directory as the executing program
            catalog.Catalogs.Add(directoryCatalog);

            //Create the CompositionContainer with the parts in the catalog
            var container = new CompositionContainer(catalog);

            try
            {
                //Fill the imports of this object
                container.ComposeParts(this);
            }
            catch (Exception ex)
            {
                Out.WriteLine("Unable to load plugins: {0}", ex.Message);
            }

        }
コード例 #7
0
ファイル: Program.cs プロジェクト: modulexcite/cDashboard
 private Program()
 {
     var catalog = new AggregateCatalog();
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
     catalog.Catalogs.Add(new DirectoryCatalog(Environment.CurrentDirectory));
     _container = new CompositionContainer(catalog);
     try
     {
         _container.ComposeParts(this);
     }
     catch (System.Reflection.ReflectionTypeLoadException v)
     {
         foreach (var c in v.LoaderExceptions)
             Console.WriteLine(c.ToString());
     }
     catch (CompositionException e) {
         Console.WriteLine(e.ToString());
     }
     if (plugins != null)
     {
         foreach (var q in plugins)
         {
             Console.WriteLine(q.Metadata.name);
         }
         PluginContainer.plugins= plugins;
     }
     else
         Console.WriteLine("No plugins loaded");
 }
コード例 #8
0
ファイル: ModuleLoader.cs プロジェクト: jden/scriptcs
        public void Load(IModuleConfiguration config, string modulePackagesPath, string extension, params string[] moduleNames)
        {
            _logger.Debug("Loading modules from: " + modulePackagesPath);
            var paths = _resolver.GetAssemblyPaths(modulePackagesPath, string.Empty);
            var catalog = new AggregateCatalog();
            foreach (var path in paths)
            {
                _addToCatalog(path, catalog);
            }

            var container = new CompositionContainer(catalog);
            var lazyModules = _getModules(container);
            var modules = lazyModules
                .Where(m => moduleNames.Contains(m.Metadata.Name) ||
                    (extension != null && m.Metadata.Extensions != null && (m.Metadata.Extensions.Split(',').Contains(extension))))
                .Select(m => m.Value);

            _logger.Debug("Initializing modules");
            foreach (var module in modules)
            {
                _logger.Debug(string.Format("Initializing module:{0}", module.GetType().FullName));
                module.Initialize(config);
            }

            _logger.Debug("Modules initialized");
        }
コード例 #9
0
    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;
      }
    }
コード例 #10
0
 public static void Init()
 {
     AggregateCatalog catalog = new AggregateCatalog();
     catalog.Catalogs.Add(new AssemblyCatalog(typeof (DataAccessAssembly).Assembly));
     catalog.Catalogs.Add(new AssemblyCatalog(typeof (AzureUtilitiesMockAssembly).Assembly));
     MefBase.Container = new CompositionContainer(catalog, true);
 }
コード例 #11
0
        /// <summary>
        /// Initializes the MEF Container.
        /// </summary>
        /// <param name="root">The root.</param>
        public static void Initialize(object root)
        {
            if (root == null)
            throw new NullReferenceException("MEF root");

             if (_instance == null) {
            lock (_syncRoot) {
               if (_instance == null) {
                  string exePath = null;
                  string path = null;
                  if (Assembly.GetEntryAssembly() != null) {
                     exePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                  } else {
                     exePath = Path.GetDirectoryName(root.GetType().Assembly.Location);
                  }
                  path = Path.Combine(exePath, "\\plugins");
                  if (!Directory.Exists(path))
                     Directory.CreateDirectory(path);

                  var catalog = new AggregateCatalog();
                  if (path != null)
                     catalog.Catalogs.Add(new DirectoryCatalog(path));
                  if (exePath != null)
                     catalog.Catalogs.Add(new DirectoryCatalog(exePath));
                  catalog.Catalogs.Add(new AssemblyCatalog(root.GetType().Assembly));

                  _instance = new CompositionContainer(catalog);
                  _instance.ComposeParts(root);

               }
            }
             }
        }
コード例 #12
0
ファイル: Plugins.cs プロジェクト: txdv/Builder
        public static IPlugins GetPlugins(ITranslator translator, IAssemblyInfo config)
        {
            string path = null;
            if (!string.IsNullOrWhiteSpace(config.PluginsPath))
            {
                path = Path.Combine(translator.FolderMode ? translator.Location : Path.GetDirectoryName(translator.Location), config.PluginsPath);
            }
            else
            {
                path = Path.Combine(translator.FolderMode ? translator.Location : Path.GetDirectoryName(translator.Location), "Bridge" + Path.DirectorySeparatorChar + "plugins");
            }

            if (!System.IO.Directory.Exists(path))
            {
                return new Plugins() { plugins = new IPlugin[0] };
            }

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

            CompositionContainer container = new CompositionContainer(catalog);
            var plugins = new Plugins();
            container.ComposeParts(plugins);

            return plugins;
        }
コード例 #13
0
ファイル: SearchDemo.cs プロジェクト: OmerRaviv/OzCodeDemo
        public void Start()
        {
            var catalog = new AggregateCatalog();

            catalog.Catalogs.Add(new AssemblyCatalog(typeof(SearchDemo).Assembly));
            var container = new CompositionContainer(catalog);
            container.ComposeParts();

            try
            {
                var component = container.GetExport<ITestComponent>();
                if (component != null)
                    Console.WriteLine(component.Value.Message);
            }
            catch (Exception exp)
            {
                //Why does our call to 'GetExport' throw an exception?

                //Search for the string "Test" on the container variable
                //You'll find 3 instances in the Catalog.
                //Then search for ITestComponent.
                //You'll need to click "Search Deeper" to expand the search.

                //Another way to do this is to view "container.Catalog.Parts", right click it,
                //select 'Edit Filter' and enter the following predicate:
                //         [obj].Exports(typoef(ITestComponent)

                MessageBox.Show(exp.Message, "Exception caught!");
            }
        }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PluginController"/> class. 
        /// </summary>
        public PluginController()
        {
            var sensors = new AggregateCatalog();
            sensors.Catalogs.Add(new AssemblyCatalog(typeof(PluginController).Assembly));
            var directoryName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            if (directoryName == null)
            {
                return;
            }

            var path = directoryName.Replace("file:\\", string.Empty);
            {
                sensors.Catalogs.Add(new DirectoryCatalog(path));
                var compositonContainer = new CompositionContainer(sensors);
                try
                {
                    compositonContainer.ComposeParts(this);
                }
                catch (CompositionException compositionException)
                {
                    Debug.WriteLine(compositionException.ToString());
                }
            }

            if (this.plugins != null)
            {
                this.loadedPlugins = new ReadOnlyCollection<IPlugin>(this.plugins.Select(plugin => plugin.Value).ToList());
            }

            if (this.menuPlugins != null)
            {
                this.menuCommandPlugins = new ReadOnlyCollection<IMenuCommandPlugin>(this.menuPlugins.Select(plugin => plugin.Value).ToList());
            }
        }
コード例 #15
0
ファイル: Main.cs プロジェクト: jorgeds001/CodeSamples
		public static void Main (string[] args)
		{
			var bootStrapper = new Bootstrapper();

            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in same directory where the application is running!
            var currentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(MainClass)).Location) ?? "./";
            catalog.Catalogs.Add(new DirectoryCatalog(currentPath));

            //Create the CompositionContainer with the parts in the catalog
            var container = new CompositionContainer(catalog);
            
            //Fill the imports of this object
            try
            {
                container.ComposeParts(bootStrapper);
            }
            catch (CompositionException compositionException)
            {
                Console.WriteLine(compositionException.ToString());
            }

            //Prints all the languages that were found into the application directory
            var i = 0;
            foreach (var language in bootStrapper.Languages)
            {
                Console.WriteLine("[{0}] {1} by {2}.\n\t{3}\n", language.Version, language.Name, language.Author, language.Description);
                i++;
            }
            Console.WriteLine("It has been found {0} supported languages",i);
            Console.ReadKey();
		}
コード例 #16
0
 /// <summary>
 /// Registers the dependencies (via convention) within this application.
 /// </summary>
 /// <param name="registrations">The dependency registrations/conventions to wire up.</param>
 /// <param name="catalog">An AggregateCatalog that can be added to if dependencies reside in an external assembly, i.e. BCL.</param>
 public void Register(RegistrationBuilder registrations, AggregateCatalog catalog)
 {
     registrations.ForTypesDerivedFrom<ILogger>()
         .SetCreationPolicy(CreationPolicy.Shared)
         .ExportInterfaces()
         .Export();
 }
コード例 #17
0
        protected override ComposablePartCatalog CreateCatalog() {
            _idePath = GetDevEnvIdePath();

            EnumerateAssemblies(_knownProductAssemblyPaths, Path.GetDirectoryName(GetType().Assembly.GetAssemblyPath()));
            EnumerateAssemblies(_knownVsAssemblyPaths, Path.Combine(_idePath, @"PrivateAssemblies\"));
            EnumerateAssemblies(_knownVsAssemblyPaths, Path.Combine(_idePath, @"CommonExtensions\"));

            var aggregateCatalog = new AggregateCatalog();
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            try {
                var nugetAssemblies = GetNugetAssemblies().ToList();
                if (nugetAssemblies.Any()) {
                    FindInCurrentAssemblyFolder(nugetAssemblies, aggregateCatalog);
                }

                foreach (var assemblyName in GetBinDirectoryAssemblies()) {
                    LoadAssembly(assemblyName, _knownProductAssemblyPaths, aggregateCatalog);
                }

                foreach (var assemblyName in GetVsAssemblies()) {
                    LoadAssembly(assemblyName, _knownVsAssemblyPaths, aggregateCatalog);
                }

                ValidateCatalog(aggregateCatalog);
                return aggregateCatalog;
            } finally {
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
            }
        }
コード例 #18
0
ファイル: Bootstrapper.cs プロジェクト: mikeminutillo/task
        public Runner Init(IFeedbackProvider feedbackProvider, string[] args)
        {
            var catalog = new AggregateCatalog(new AssemblyCatalog(typeof(Bootstrapper).Assembly));

            var currentDir = Environment.CurrentDirectory;
            var assemblyDir = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath).Directory.FullName;

            var paths = new string[]
            {
                assemblyDir,
                Path.Combine(assemblyDir, "Tasks"),
                currentDir,
                Path.Combine(currentDir, "Tasks")
            }.Unique();

            var dirCatalogs = paths.Where(x => Directory.Exists(x))
                                   .Select(x => new DirectoryCatalog(x, "*.Tasks.dll"));
            dirCatalogs.Apply(x => catalog.Catalogs.Add(x));

            var container = new CompositionContainer(catalog);

            var parsed = new ArgumentParser().Parse(args);
            var runner = new Runner(parsed.ActualArgs.ToArray());

            var batch = new CompositionBatch();
            batch.AddExportedValue<IFeedbackProvider>(feedbackProvider);
            parsed.Options.Apply(x => batch.AddExportedValue<string>(x.Item1, x.Item2));
            parsed.Switches.Apply(x => batch.AddExportedValue<bool>(x, true));
            batch.AddPart(runner);
            container.Compose(batch);

            return runner;
        }
コード例 #19
0
        public void WhenInitializingAModuleWithNoCatalogPendingToBeLoaded_ThenInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

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

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

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

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

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

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

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

            Assert.IsFalse(module.Initialized);

            moduleInitializer.Initialize(moduleInfo);

            Assert.IsTrue(module.Initialized);
        }
コード例 #20
0
ファイル: App.xaml.cs プロジェクト: JogoShugh/IronRubyMef
        private bool Compose()
        {
            var catalog = new System.ComponentModel.Composition.Hosting.AggregateCatalog();
            //            var catalog = new AggregatingComposablePartCatalog();
            catalog.Catalogs.Add(
                new RubyCatalog(new RubyPartFile("calculator_ops.rb")));
            catalog.Catalogs.Add(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new System.ComponentModel.Composition.Hosting.CompositionContainer(catalog);
            //_container. AddPart(this);
            var batch = new System.ComponentModel.Composition.Hosting.CompositionBatch();
            batch.AddPart(this);
            //_container.AddPart(this);
            //_container.Compose(this);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                return false;
            }
            return true;
        }
コード例 #21
0
        public void WhenInitializingAModuleWithACatalogPendingToBeLoaded_ThenLoadsTheCatalogInitializesTheModule()
        {
            var aggregateCatalog = new AggregateCatalog(new AssemblyCatalog(typeof(MefModuleInitializer).Assembly));
            var compositionContainer = new CompositionContainer(aggregateCatalog);
            compositionContainer.ComposeExportedValue(aggregateCatalog);

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

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

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

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

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

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

            moduleInitializer.Initialize(moduleInfo);

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

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

            Assert.IsTrue(module.Initialized);
        }
コード例 #22
0
        private static IEnumerable<ComposablePartDefinition> GetRequiredPrismPartsToRegister(AggregateCatalog aggregateCatalog)
        {
            List<ComposablePartDefinition> partsToRegister = new List<ComposablePartDefinition>();
            var catalogWithDefaults = GetDefaultComposablePartCatalog();
            foreach (var part in catalogWithDefaults.Parts)
            {
                foreach (var export in part.ExportDefinitions)
                {
                    bool exportAlreadyRegistered = false;
                    foreach (var registeredPart in aggregateCatalog.Parts)
                    {
                        foreach (var registeredExport in registeredPart.ExportDefinitions)
                        {
                            if (string.Compare(registeredExport.ContractName, export.ContractName, StringComparison.Ordinal) == 0)
                            {
                                exportAlreadyRegistered = true;
                                break;
                            }
                        }
                    }

                    if (exportAlreadyRegistered != false) continue;
                    if (!partsToRegister.Contains(part))
                    {
                        partsToRegister.Add(part);
                    }
                }
            }
            return partsToRegister;
        }
コード例 #23
0
        /// <summary>
        /// Default private constructor.
        /// </summary>
        private ExtensionManager()
        {
            if (!Config.DisableComposition)
            {
                // Let MEF scan for imports
                var catalog = new AggregateCatalog();

                catalog.Catalogs.Add(Config.DisableCatalogSearch ? new DirectoryCatalog("Bin", "Piranha*.dll") : new DirectoryCatalog("Bin"));

            #if !NET40
                if (!System.Web.Compilation.BuildManager.IsPrecompiledApp)
                {
            #endif
                    try
                    {
                        // This feature only exists for Web Pages
                        catalog.Catalogs.Add(new AssemblyCatalog(Assembly.Load("App_Code")));
                    }
                    catch { }
            #if !NET40
                }
            #endif

                Container = new CompositionContainer(catalog);
                Container.ComposeParts(this);
            }
        }
コード例 #24
0
    static async Task AsyncMain()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new DirectoryCatalog("."));

        CompositionContainer compositionContainer = new CompositionContainer(catalog);

        Console.Title = "Samples.MefExtensionEndpoint";
        LogManager.Use<DefaultFactory>().Level(LogLevel.Info);
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.MefExtensionEndpoint");
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.EnableInstallers();
        await RunCustomizeConfiguration(compositionContainer, endpointConfiguration);
        await RunBeforeEndpointStart(compositionContainer);
        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);
        await RunAfterEndpointStart(compositionContainer, endpoint);
        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await RunBeforeEndpointStop(compositionContainer, endpoint);
            await endpoint.Stop();
        }
        await RunAfterEndpointStop(compositionContainer);
    }
コード例 #25
0
ファイル: Program.cs プロジェクト: mind0n/hive
        /// <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();
                }
            }
        }
コード例 #26
0
ファイル: CachedVsInfo.cs プロジェクト: omnimark/PTVS
        public CachedVsInfo(AggregateCatalog catalog, List<Type> packages) {
            Catalog = catalog;
            Packages = packages;

            foreach (var package in Packages) {
                var attrs = package.GetCustomAttributes(typeof(ProvideLanguageServiceAttribute), false);
                foreach (ProvideLanguageServiceAttribute attr in attrs) {
                    foreach (var type in package.Assembly.GetTypes()) {
                        if (type.GUID == attr.LanguageServiceSid) {
                            var info = new LanguageServiceInfo(attr);
                            LangServicesByGuid[attr.LanguageServiceSid] = info;
                            LangServicesByName[attr.LanguageName] = info;

                            break;
                        }
                    }
                }

                var extensions = package.GetCustomAttributes(typeof(ProvideLanguageExtensionAttribute), false);
                foreach (ProvideLanguageExtensionAttribute attr in extensions) {
                    LanguageServiceInfo info;
                    if (LangServicesByGuid.TryGetValue(attr.LanguageService, out info)) {
                        _languageNamesByExtension[attr.Extension] = info.Attribute.LanguageName;
                    }
                }
            }
        }
コード例 #27
0
        public void TestMefStatusReportable()
        {
            string dir = AssemblyDirectory;

            //Lets get the nlog status reportable from MEF directory..
            CompositionContainer _container;
            //An aggregate catalog that combines multiple catalogs
            var catalog = new AggregateCatalog();
            //Adds all the parts found in the same assembly as the Program class
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(TestMEF).Assembly));
            catalog.Catalogs.Add(new DirectoryCatalog(AssemblyDirectory));

            //Create the CompositionContainer with the parts in the catalog
            _container = new CompositionContainer(catalog);

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

            reporter.Report(2,1,"Test Report");
        }
コード例 #28
0
ファイル: StatementHandler.cs プロジェクト: QANTau/QPAS
        /// <summary>
        /// This method loads the plugins.
        /// </summary>
        private void AssembleComponents()
        {
            var catalog = new AggregateCatalog();

            //Note: we load not only from the plugins folder, but from this assembly as well.
            var executingAssemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            if (Directory.Exists(Environment.CurrentDirectory + "\\Plugins"))
            {
                catalog.Catalogs.Add(new DirectoryCatalog("Plugins"));
            }

            catalog.Catalogs.Add(executingAssemblyCatalog);

            var container = new CompositionContainer(catalog);

            try
            {
                container.ComposeParts(this);
            }
            catch (CompositionException compositionException)
            {
                _dialogService.ShowMessageAsync(_mainVm, "Error", string.Format("There was an error loading plugins: {0}", compositionException)).Forget();
            }
        }
コード例 #29
0
ファイル: PluginInfrastructre.cs プロジェクト: kiszu/ForBlog
        public void Initialize()
        {
            var catalog = new AggregateCatalog();

            //Adds the program's assembly
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(PluginInfrastructre).Assembly));


            string programassembly = System.Reflection.Assembly.GetAssembly(typeof(PluginInfrastructre)).Location;

            string programpath = Path.GetDirectoryName(programassembly);

            //add the program's path
            catalog.Catalogs.Add(new DirectoryCatalog(programpath));

            _container = new CompositionContainer(catalog);

            try
            {
                //Initialize types found and assign new instances to Plugins
                Plugins = _container.GetExportedValues<IPlugin>();
                
            }
            catch (CompositionException compositionException)
            {
                throw;
            }
        }
コード例 #30
0
ファイル: App.xaml.cs プロジェクト: keremkusmezer/ILSpy
		public App()
		{
			var cmdArgs = Environment.GetCommandLineArgs().Skip(1);
			App.CommandLineArguments = new CommandLineArguments(cmdArgs);
			if (App.CommandLineArguments.SingleInstance ?? true) {
				cmdArgs = cmdArgs.Select(FullyQualifyPath);
				string message = string.Join(Environment.NewLine, cmdArgs);
				if (SendToPreviousInstance("ILSpy:\r\n" + message, !App.CommandLineArguments.NoActivate)) {
					Environment.Exit(0);
				}
			}
			InitializeComponent();
			
			var catalog = new AggregateCatalog();
			catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly));
			catalog.Catalogs.Add(new DirectoryCatalog(".", "*.Plugin.dll"));
			
			compositionContainer = new CompositionContainer(catalog);
			
			Languages.Initialize(compositionContainer);
			
			if (!Debugger.IsAttached) {
				AppDomain.CurrentDomain.UnhandledException += ShowErrorBox;
				Dispatcher.CurrentDispatcher.UnhandledException += Dispatcher_UnhandledException;
			}
			
			EventManager.RegisterClassHandler(typeof(Window),
			                                  Hyperlink.RequestNavigateEvent,
			                                  new RequestNavigateEventHandler(Window_RequestNavigate));
		}
コード例 #31
0
        /// <summary>
        /// Registra os requisitos.
        /// </summary>
        /// <param name="aggregateCatalog"></param>
        /// <returns></returns>
        public static System.ComponentModel.Composition.Hosting.AggregateCatalog RegisterRequiredServicesIfMissing(System.ComponentModel.Composition.Hosting.AggregateCatalog aggregateCatalog)
        {
            aggregateCatalog.Require("aggregateCatalog").NotNull();
            var item = new DefaultCatalog(GetRequiredPartsToRegister(aggregateCatalog));

            aggregateCatalog.Catalogs.Add(item);
            return(aggregateCatalog);
        }