当前位置: 首页>>代码示例>>C#>>正文


C# CompositionContainer.GetExports方法代码示例

本文整理汇总了C#中System.ComponentModel.Composition.Hosting.CompositionContainer.GetExports方法的典型用法代码示例。如果您正苦于以下问题:C# CompositionContainer.GetExports方法的具体用法?C# CompositionContainer.GetExports怎么用?C# CompositionContainer.GetExports使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.ComponentModel.Composition.Hosting.CompositionContainer的用法示例。


在下文中一共展示了CompositionContainer.GetExports方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MainMenuViewModel

        public MainMenuViewModel(CompositionContainer container)
        {
            _topLevelMenuItems = new ObservableCollection<MenuItemViewModel>();
            _styleSelector = new MainMenuItemStyleSelector();
            
            var menuItemImports =  container.GetExports<IMenuItem, IMenuItemMetaData>();
            var globalCommandImports = container.GetExports<IGlobalCommand>();

            var menuBuilder = new MenuBuilder(globalCommandImports);

            foreach (var import in menuItemImports.Where(x => x.Metadata.IsMainMenuItem))
            {
                menuBuilder.AddItem(import.Value, import.Metadata);
            }

            foreach (var rootItem in menuBuilder.Build().Children)
            {
                MenuItemViewModel viewModel;

                if (rootItem is MenuSeparatorModel)
                {
                    viewModel  = new MenuSeparatorViewModel();
                }
                else
                {
                    viewModel = new MenuItemViewModel(null, rootItem.HeaderText, rootItem.Command, rootItem.GestureText, rootItem.Children);
                }

                _topLevelMenuItems.Add(viewModel);
            }
        }
开发者ID:HaKDMoDz,项目名称:Zazumo,代码行数:31,代码来源:MainMenuViewModel.cs

示例2: Main

        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">
        /// The args. 
        /// </param>
        public static void Main(string[] args)
        {
            WriteSignature();

            using (AggregateCatalog aggregateCatalog = new AggregateCatalog())
            {
                RegistrationBuilder registrationBuilder = new RegistrationBuilder();

                registrationBuilder.ForTypesDerivedFrom<ICommand>()
                                   .Export(conf => conf.AsContractName(AttributedModelServices.GetContractName(typeof(ICommand))))
                                   .SetCreationPolicy(CreationPolicy.NonShared);
                
                aggregateCatalog.Catalogs.Add(new ApplicationCatalog(registrationBuilder));

                string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string pluginPath = Path.Combine(appPath, "plugins");
                if (Directory.Exists(pluginPath))
                    aggregateCatalog.Catalogs.Add(new DirectoryCatalog(pluginPath, registrationBuilder));

                using (CompositionContainer container = new CompositionContainer(aggregateCatalog))
                {
                    ICommandProvider[] providers = container.GetExports<ICommandProvider>().Select(l => l.Value).ToArray();
                    Type[] commands = providers.SelectMany(p => p.GetCommands()).ToArray();

                    Func<Type, object> mefActivator =
                        t =>
                        {
                            if (!typeof(ICommand).IsAssignableFrom(t))
                                return DefaultActivator.Instance.CreateInstance(t);

                            ImportDefinition importDefinition = new ImportDefinition(ed => (string)ed.Metadata[CompositionConstants.ExportTypeIdentityMetadataName] == AttributedModelServices.GetTypeIdentity(t),
                                                                                     AttributedModelServices.GetContractName(typeof(ICommand)),
                                                                                     ImportCardinality.ExactlyOne,
                                                                                     false,
                                                                                     true);

                            return container.GetExports(importDefinition).First().Value;
                        };

                    ArgumentParserSettings parserSettings = new ArgumentParserSettings
                                                            {
                                                                TypeActivator = new DelegateActivator(mefActivator)
                                                            };

                    ArgumentParser<ICommand> argumentParser = new ArgumentParser<ICommand>(parserSettings, commands);
                    ICommand command;
                    if (argumentParser.TryParse(args, out command))
                    {
                        command.Invoke(container);
                    }
                }
            }
        }
开发者ID:LBiNetherlands,项目名称:LBi.LostDoc,代码行数:59,代码来源:Program.cs

示例3: AixmConverter

        public AixmConverter()
        {
            List<Assembly> source = AppDomain.CurrentDomain.GetAssemblies().ToList<Assembly>();
            foreach (var asm in source)
            {
                AssemblyCatalog catalog = new AssemblyCatalog(asm);
                CompositionContainer mefContainer = new CompositionContainer(catalog, true);
                var plugins = mefContainer.GetExports<Func<IAixmConverter, JObject, XElement, IEnumerable<JObject>>, IAixmConverterMetadata>().ToArray();
                _elementReaders.AddRange(plugins);
                _elementWriters.AddRange(mefContainer.GetExports<Action<IAixmConverter,int, JObject, XmlWriter>, IAixmConverterMetadata>().ToArray());

            }
            _elementWriters = _elementWriters.OrderBy(k => k.Metadata.WriteOrder).ToList();
        }
开发者ID:s-innovations,项目名称:S-Innovations.Aixm,代码行数:14,代码来源:AixmConverter.cs

示例4: Main

        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">
        /// The args. 
        /// </param>
        public static void Main(string[] args)
        {
            WriteSignature();

            using (AggregateCatalog aggregateCatalog = new AggregateCatalog())
            {
                aggregateCatalog.Catalogs.Add(new ApplicationCatalog());

                string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string pluginPath = Path.Combine(appPath, "plugins");
                if (Directory.Exists(pluginPath))
                    aggregateCatalog.Catalogs.Add(new DirectoryCatalog(pluginPath));

                using (CompositionContainer container = new CompositionContainer(aggregateCatalog))
                {
                    ICommandProvider[] providers = container.GetExports<ICommandProvider>().Select(l => l.Value).ToArray();
                    var commands = providers.SelectMany(p => p.GetCommands()).ToArray();

                    ArgumentParser<ICommand> argumentParser = new ArgumentParser<ICommand>(commands);
                    ICommand command;
                    if (argumentParser.TryParse(args, out command))
                    {
                        command.Invoke(container);
                    }
                }
            }
        }
开发者ID:ppittle,项目名称:LBi.LostDoc,代码行数:33,代码来源:Program.cs

示例5: LoadContainer

        public static void LoadContainer(IUnityContainer container, string path, string pattern)
        {
            var directoryCatalog = new DirectoryCatalog(path, pattern);
            var importDefinition = BuildImportDefinition();

            try
            {
                using (var aggregateCatalog = new AggregateCatalog())
                {
                    aggregateCatalog.Catalogs.Add(directoryCatalog);
                    using (var componsitionContainer = new CompositionContainer(aggregateCatalog))
                    {
                        IEnumerable<Export> exports = componsitionContainer.GetExports(importDefinition);
                        IEnumerable<IModule> modules = exports.Select(export => export.Value as IModule).Where(m => m != null);

                        foreach (IModule module in modules)
                        {
                            module.Initialize(container);
                        }
                    }
                }
            }
            catch (ReflectionTypeLoadException typeLoadException)
            {
                var builder = new StringBuilder();

                foreach (Exception loaderException in typeLoadException.LoaderExceptions)
                {
                    builder.AppendFormat("{0}\n", loaderException.Message);
                }

                throw new TypeLoadException(builder.ToString(), typeLoadException);
            }
        }
开发者ID:logic01,项目名称:GreenMachine,代码行数:34,代码来源:ModuleLoader.cs

示例6: GetValuesByType

        public void GetValuesByType()
        {
            var cat = CatalogFactory.CreateDefaultAttributed();

            var container = new CompositionContainer(cat);

            string itestName = AttributedModelServices.GetContractName(typeof(ITest));

            var e1 = container.GetExportedValues<ITest>();
            var e2 = container.GetExports<ITest, object>(itestName);

            Assert.IsInstanceOfType(e1.First(), typeof(T1), "First should be T1");
            Assert.IsInstanceOfType(e1.Skip(1).First(), typeof(T2), "Second should be T2");

            Assert.IsInstanceOfType(e2.First().Value, typeof(T1), "First should be T1");
            Assert.IsInstanceOfType(e2.Skip(1).First().Value, typeof(T2), "Second should be T2");

            CompositionContainer childContainer = new CompositionContainer(container);
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new T1());
            container.Compose(batch);
            var t1 = childContainer.GetExportedValue<ITest>();
            var t2 = childContainer.GetExport<ITest, object>(itestName);

            Assert.IsInstanceOfType(t1, typeof(T1), "First (resolved) should be T1");
            Assert.IsInstanceOfType(t2.Value, typeof(T1), "First (resolved) should be T1");
        }
开发者ID:nlhepler,项目名称:mono,代码行数:27,代码来源:ComponentServicesTests.cs

示例7: LoadCodecs

		public static void LoadCodecs(string path = null, string search = null) {
			if (path == null)
				path = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath);

		    if (search == null)
		        search = "Dicom.Native*.dll";

			var log = LogManager.Default.GetLogger("Dicom.Imaging.Codec");
		    log.Debug("Searching {path}\\{wildcard} for Dicom codecs", path, search);

		    var foundAnyCodecs = false;

		    DirectoryCatalog catalog;
		    try {
		        catalog = new DirectoryCatalog(path, search);
		    }
		    catch (Exception ex) {
		        log.Error("Error encountered creating new DirectCatalog({path}, {search}) - {@exception}", path, search, ex);
		        throw;
		    }

			var container = new CompositionContainer(catalog);
			foreach (var lazy in container.GetExports<IDicomCodec>()) {
			    foundAnyCodecs = true;
				var codec = lazy.Value;
				log.Debug("Codec: {codecName}", codec.TransferSyntax.UID.Name);
				_codecs[codec.TransferSyntax] = codec;
			}

		    if (!foundAnyCodecs) {
		        log.Warn("No Dicom codecs were found after searching {path}\\{wildcard}", path, search);
		    }
		}
开发者ID:dremerdt,项目名称:fo-dicom,代码行数:33,代码来源:DicomTranscoder.cs

示例8: TreatyHelper

 public TreatyHelper()
 {
     var catalog = new AssemblyCatalog(this.GetType().Assembly);
     var container = new CompositionContainer(catalog);
     
     this.treaties = container.GetExports<ITreatyProvider>().ToList();
 }
开发者ID:JaredReisinger,项目名称:TreatyOfBabel.NET,代码行数:7,代码来源:TreatyHelper.cs

示例9: WhenExportIsFiltered_ThenPartIsAvailableButNotExport

	public void WhenExportIsFiltered_ThenPartIsAvailableButNotExport()
	{
		var catalog = new TypeCatalog(typeof(Foo));
		var filtered = new FilteringReflectionCatalog(catalog)
		{
			ExportFilter = export => !(export.ExportingMember.MemberType == System.Reflection.MemberTypes.Property),
		};

		var container = new CompositionContainer(filtered);

		var exports = container.GetExports<IFoo>();
		var barExports = container.GetExports<IBar>();

		Assert.True(exports.Any());
		Assert.False(barExports.Any());
	}
开发者ID:netfx,项目名称:extensions,代码行数:16,代码来源:FilteringReflectionCatalogSpec.cs

示例10: LoadServers

        /// <summary>
        /// Loads all SharpShell servers from an assembly.
        /// </summary>
        /// <param name="path">The path to the assembly.</param>
        /// <returns>A ServerEntry for each SharpShell server in the assembly.</returns>
        public static IEnumerable<ServerEntry> LoadServers(string path)
        {
            //  Storage for the servers.
            var servers = new List<ServerEntry>();

            try
            {
                //  Create an assembly catalog for the assembly and a container from it.
                var catalog = new AssemblyCatalog(Path.GetFullPath(path));
                var container = new CompositionContainer(catalog);

                //  Get all exports of type ISharpShellServer.
                var serverTypes = container.GetExports<ISharpShellServer>();

                //  Go through each servertype (creating the instance from the lazy).
                foreach(var serverType in serverTypes)
                {
                    ISharpShellServer server = null;
                    try
                    {
                        server = serverType.Value;
                    }
                    catch (Exception)
                    {
                        servers.Add(new ServerEntry
                        {
                            ServerName = "Invalid",
                            ServerPath = path,
                            ServerType = ServerType.None,
                            ClassId = new Guid(),
                            Server = null,
                            IsInvalid = true
                        });
                        continue;
                    }

                    //  Yield a server entry for the server type.
                    servers.Add(new ServerEntry
                                          {
                                              ServerName = server.DisplayName, 
                                              ServerPath = path,
                                              ServerType = server.ServerType,
                                              ClassId = server.ServerClsid,
                                              Server = server
                                          });

                }
            }
            catch (Exception)
            {
                //  It's almost certainly not a COM server.
                MessageBox.Show("The file '" + Path.GetFileName(path) + "' is not a SharpShell Server.", "Warning");
            }

            //  Return the servers.
            return servers;
        }
开发者ID:mleo1,项目名称:sharpshell,代码行数:62,代码来源:ServerManagerApi.cs

示例11: FilterBasedOnMetadataUsingContainsMetadataTest

        public void FilterBasedOnMetadataUsingContainsMetadataTest()
        {
            var catalog = new AssemblyCatalog(typeof(FilteringCatalogTests).Assembly);
            var filteredCatalog = new FilteringCatalog(catalog, new ContainsMetadata("key", "value"));
            var container = new CompositionContainer(filteredCatalog);
            var components = container.GetExports<IMetadataComponent>();

            Assert.That(components, Is.Not.Null);
            Assert.That(components.Count(), Is.EqualTo(1));
        }
开发者ID:damonrpayne,项目名称:MefContrib,代码行数:10,代码来源:FilteringCatalogTests.cs

示例12: Register

        /// <summary>
        /// The register.
        /// </summary>
        /// <param name="container">
        /// The container.
        /// </param>
        public static void Register(IWindsorContainer container)
        {
            var catalog =
                new CatalogBuilder().ForAssembly(typeof(IComponentRegistrarMarker).Assembly).ForMvcAssembly(
                    Assembly.GetExecutingAssembly()).ForMvcAssembliesInDirectory(HttpRuntime.BinDirectory, "Leatn*.dll")
                    .Build();

            var compositionContainer = new CompositionContainer(catalog);
            compositionContainer.GetExports<IComponentRegistrar>().ForeEach(e => e.Value.Register(container));
        }
开发者ID:kamukondiwa,项目名称:SimpleBlog,代码行数:16,代码来源:ComponentRegistrar.cs

示例13: Main

        public static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("File Watch Directory must be specifed");
                Console.WriteLine("usage: engine.exe path");
                return -1;
            }

            try
            {
                // Example of convention-based approach
                var registration = new RegistrationBuilder();
                registration.ForType<Logger>().Export<ILogger>();
                var assemblyCatalog = new AssemblyCatalog(typeof(Logger).Assembly, registration);

                var catalog = new AggregateCatalog(
                    assemblyCatalog,
                    new DirectoryCatalog(@".\addins"));

                using (var container = new CompositionContainer(catalog))
                {
                    var engine = new ProcessorEngine(new DirectoryInfo(args[0]));

                    // Bind exports to imports
                    container.ComposeParts(engine);

                    var exports = container.GetExports<IFileProcessor, IFileProcessorMetadata>().ToList();

                    Console.WriteLine("{0} File Processor(s) available", exports.Count);

                    if (exports.Count > 0)
                    {
                        foreach (var export in exports)
                        {
                            Console.WriteLine("{0} file type supported", export.Metadata.SupportedExtension);
                        }
                        engine.ProcessFiles();
                    }
                    else
                    {
                        Console.WriteLine("Add File Processors to the Add-in directory");
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
                return -1;
            }
            Console.ReadLine();
            return 0;
        }
开发者ID:jasongerard,项目名称:MefExample,代码行数:54,代码来源:Program.cs

示例14: Parts_are_filtered_based_on_shared_lifetime_using_HasCreationPolicy_filter

        public void Parts_are_filtered_based_on_shared_lifetime_using_HasCreationPolicy_filter()
        {
            var catalog = new AssemblyCatalog(typeof(FilteringCatalogTests).Assembly);
            var filteredCatalog = new FilteringCatalog(catalog, new HasCreationPolicy(CreationPolicy.Shared));
            var container = new CompositionContainer(filteredCatalog);
            var components = container.GetExports<ILifetimeComponent>();

            Assert.That(components, Is.Not.Null);
            Assert.That(components.Count(), Is.EqualTo(1));
            Assert.That(components.First().Value.GetType(), Is.EqualTo(typeof(LifetimeComponent2)));
        }
开发者ID:doublekill,项目名称:MefContrib,代码行数:11,代码来源:FilteringCatalogTests.cs

示例15: FilterBasedOnNonSharedLifetimeUsingHasCreationPolicyTest

        public void FilterBasedOnNonSharedLifetimeUsingHasCreationPolicyTest()
        {
            var catalog = new AssemblyCatalog(typeof(FilteringCatalogTests).Assembly);
            var filteredCatalog = new FilteringCatalog(catalog, new HasCreationPolicy(CreationPolicy.NonShared));
            var container = new CompositionContainer(filteredCatalog);
            var components = container.GetExports<ILifetimeComponent>();

            Assert.That(components, Is.Not.Null);
            Assert.That(components.Count(), Is.EqualTo(1));
            Assert.That(components.First().Value.GetType(), Is.EqualTo(typeof(LifetimeComponent3)));
        }
开发者ID:damonrpayne,项目名称:MefContrib,代码行数:11,代码来源:FilteringCatalogTests.cs


注:本文中的System.ComponentModel.Composition.Hosting.CompositionContainer.GetExports方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。