/// <summary> /// Searchs for types with custom metadata type based. /// </summary> /// <typeparam name="T">Type to search.</typeparam> /// <returns>This object.</returns> public SerializeContainer DiscoverCustomMetadataTypes <T>() { var cpds = (from cpd in container.Catalog where cpd.Metadata.Any(x => String.Compare(x.Value.ToString(), typeof(T).FullName, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(x.Key.ToString(), typeof(T).FullName, StringComparison.OrdinalIgnoreCase) == 0) select cpd).ToList(); foreach (var v in cpds) { knownTypes.Add(ReflectionModelServices.GetPartType(v).Value); } return(this); }
private static Type ComposablePartExportType <T>(ComposablePartDefinition part) { if (part.ExportDefinitions.Any(def => def.Metadata.ContainsKey("ExportTypeIdentity") && def.Metadata["ExportTypeIdentity"].Equals(typeof(T).FullName) )) { return(ReflectionModelServices.GetPartType(part).Value); } return(null); }
public static bool IsPartDefinitionCacheUpToDate(this ComposablePartDefinition partDefinition) { IDictionary <string, object> cache = ReflectionModelServices.GetPartType(partDefinition).GetMetadata(); if (cache != null) { return(cache.IsAssemblyCacheUpToDate()); } else { return(false); } }
/// <summary> /// Clones the non-shared to avoid object instance reuse, /// which happens if you cache the part definition. /// </summary> private IEnumerable <ComposablePartDefinition> CloneNonSharedParts() { return(this.nonSharedParts .AsParallel() .Where(part => part != null) .Select(def => ReflectionModelServices.CreatePartDefinition( ReflectionModelServices.GetPartType(def), true, new Lazy <IEnumerable <ImportDefinition> >(() => def.ImportDefinitions), new Lazy <IEnumerable <ExportDefinition> >(() => def.ExportDefinitions), new Lazy <IDictionary <string, object> >(() => def.Metadata), this))); }
public static IDictionary <string, object> WritePartDefinition(ComposablePartDefinition part, bool writeAssembly) { Assumes.NotNull(part); IDictionary <string, object> cache = new Dictionary <string, object>(); Lazy <Type> partType = ReflectionModelServices.GetPartType(part); cache.WriteMetadata(part.Metadata); cache.WriteLazyTypeForPart(partType, writeAssembly); cache.WriteValue <bool>(AttributedCacheServices.CacheKeys.IsDisposalRequired, ReflectionModelServices.IsDisposalRequired(part), false); return(cache); }
private ComposablePartDefinition CreateWrapped(ComposablePartDefinition partDefinition, Type type) { IEnumerable <ExportDefinition> exports = partDefinition.ExportDefinitions.Select(e => this.CreateWrapped(e, type)).ToArray(); IEnumerable <ImportDefinition> imports = partDefinition.ImportDefinitions.Cast <ContractBasedImportDefinition>().Select(i => this.CreateWrapped(i, type)).ToArray(); return(ReflectionModelServices.CreatePartDefinition( this.CreateWrapped(ReflectionModelServices.GetPartType(partDefinition), type), ReflectionModelServices.IsDisposalRequired(partDefinition), imports.AsLazy(), exports.AsLazy(), partDefinition.Metadata.AsLazy(), null)); }
/// <summary> /// Loads extensions. /// </summary> private void LoadExtensions() { // If the plugin directory doesn't exist, abort plugin loading if (!this.extensionDirectory.Exists) { return; } // Initialize catalog AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(this.extensionDirectory.FullName)); // Load ISnippetExtractor factories string metadataName = "ExportTypeIdentity"; string targetTypeFullName = typeof(ISnippetExtractor).FullName; foreach (ComposablePartDefinition composablePartDefinition in catalog.Parts.AsEnumerable()) { // Look for composable part definition being an ISnippetExtracttor if (composablePartDefinition.ExportDefinitions.Any(d => d.Metadata.ContainsKey(metadataName) && d.Metadata[metadataName].ToString() == targetTypeFullName)) { // Fetch the extension type from the composable part definition Type extensionType = ReflectionModelServices.GetPartType(composablePartDefinition).Value; // Try to retrieve syntax attribute SyntaxAttribute syntax = Attribute.GetCustomAttribute(extensionType, typeof(SyntaxAttribute)) as SyntaxAttribute; // Add the extractor type to loaded ones if a syntax attribute is found and the type has a default contructor if (null != syntax && null != extensionType.GetConstructor(Type.EmptyTypes)) { // Create extractor factory Func <ISnippetExtractor> extractorFactory = Expression.Lambda <Func <ISnippetExtractor> >(Expression.New(extensionType)).Compile(); // Record the created fectory as a loaded one this.loadedExtractorFactories.Add(syntax.Name, extractorFactory); } } } // Lookup in loaded extractors to detect custom default extractor Func <ISnippetExtractor> customDefaultExtractorFactory; if (this.loadedExtractorFactories.TryGetValue("*", out customDefaultExtractorFactory)) { // Set the custom default extractor this.defaultExtractorFactory = customDefaultExtractorFactory; } }
public static IEnumerable <Tuple <Type, string> > GetExportedTypesWithContracts <T>(this CompositionContainer container) { foreach (var part in container.Catalog.Parts) { foreach (var def in part.ExportDefinitions) { if (def.Metadata.ContainsKey("ExportTypeIdentity") && def.Metadata["ExportTypeIdentity"].Equals(typeof(T).FullName)) { yield return(Tuple.Create(ReflectionModelServices.GetPartType(part).Value, def.ContractName)); } } } }
/// <summary> /// Extension method to searches the composition container for an export that has a matching type name. This function /// will first try to match on Type.AssemblyQualifiedName, then Type.FullName, and finally on Type.Name /// /// This method will not throw if multiple types are found matching the name, it will just return the first one it finds. /// </summary> /// <typeparam name="T">The type of the export</typeparam> /// <param name="typeName">The name of the type to find. This can be an assembly qualified name, a full name, or just the type's name</param> /// <returns>The export instance</returns> public T GetExportedValueByTypeName <T>(string typeName) where T : class { lock (_exportedValuesLockObject) { T instance; IEnumerable values; var type = typeof(T); if (_exportedValues.TryGetValue(type, out values)) { // if we've alread loaded this part, then just reserve the same one instance = values.OfType <T>().FirstOrDefault(x => x.GetType().MatchesTypeName(typeName)); if (instance != null) { return(instance); } } // we want to get the requested part without instantiating each one of that type var selectedPart = _compositionContainer.Catalog.Parts .Select(x => new { part = x, Type = ReflectionModelServices.GetPartType(x).Value }) .Where(x => type.IsAssignableFrom(x.Type)) .Where(x => x.Type.MatchesTypeName(typeName)) .Select(x => x.part) .FirstOrDefault(); if (selectedPart == null) { throw new ArgumentException("Unable to locate any exports matching the requested typeName: " + typeName, "typeName"); } var exportDefinition = selectedPart.ExportDefinitions.First(x => x.ContractName == AttributedModelServices.GetContractName(type)); instance = (T)selectedPart.CreatePart().GetExportedValue(exportDefinition); // cache the new value for next time if (values == null) { values = new List <T> { instance }; _exportedValues[type] = values; } else { ((List <T>)values).Add(instance); } return(instance); } }
private IEnumerable <ComposablePartDefinition> BuildParts(IQueryable <ComposablePartDefinition> parts) { return(parts.Select(def => ReflectionModelServices.CreatePartDefinition( ReflectionModelServices.GetPartType(def), true, new Lazy <IEnumerable <ImportDefinition> >(() => def.ImportDefinitions), new Lazy <IEnumerable <ExportDefinition> >(() => def.ExportDefinitions.Select(export => ReflectionModelServices.CreateExportDefinition( ReflectionModelServices.GetExportingMember(export), export.ContractName, new Lazy <IDictionary <string, object> >(() => VisitExport(def, export)), this))), new Lazy <IDictionary <string, object> >(() => VisitPart(def)), this))); }
//Idea from http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/ public static IEnumerable <Type> GetExportTypes <T>(this CompositionContainer mefContainer) where T : class { // look in the mef catalog to grab out all the types that are of type T return(mefContainer.Catalog.Parts.Where(part => part.ExportDefinitions .Any( def => def.Metadata.ContainsKey( "ExportTypeIdentity") && def.Metadata["ExportTypeIdentity"] .Equals( typeof(T).FullName))) .AsEnumerable() .Select(part => ReflectionModelServices.GetPartType(part).Value)); }
public Container() { var directoryCatalog = new DirectoryCatalog(@"./"); var assemblies = directoryCatalog.Parts.Select(part => ReflectionModelServices.GetPartType(part) .Value.Assembly) .Distinct(); var assemblyCatalogs = assemblies.Select(x => new AssemblyCatalog(x)); var catalog = new AggregateCatalog(assemblyCatalogs); m_Container = new CompositionContainer(catalog); var batch = new CompositionBatch(); m_Container.Compose(batch); }
public static IDictionary <string, object> WriteExportDefinition(ComposablePartDefinition owner, ExportDefinition exportDefinition) { Assumes.NotNull(owner); Assumes.NotNull(exportDefinition); LazyMemberInfo exportingMemberInfo = ReflectionModelServices.GetExportingMember(exportDefinition); IDictionary <string, object> cache = new Dictionary <string, object>(); cache.WriteContractName(exportDefinition.ContractName); cache.WriteMetadata(exportDefinition.Metadata); cache.WriteValue(AttributedCacheServices.CacheKeys.MemberType, exportingMemberInfo.MemberType, MemberTypes.TypeInfo); cache.WriteLazyAccessors(exportingMemberInfo.GetAccessors(), ReflectionModelServices.GetPartType(owner)); return(cache); }
public static ExportDefinition ReadExportDefinition(ComposablePartDefinition owner, IDictionary <string, object> cache) { Assumes.NotNull(owner); Assumes.NotNull(cache); LazyMemberInfo exportingMemberInfo = new LazyMemberInfo( cache.ReadValue <MemberTypes>(AttributedCacheServices.CacheKeys.MemberType, MemberTypes.TypeInfo), cache.ReadLazyAccessors(ReflectionModelServices.GetPartType(owner))); return(ReflectionModelServices.CreateExportDefinition( exportingMemberInfo, cache.ReadContractName(), cache.ReadLazyMetadata(), owner as ICompositionElement)); }
/// <summary> /// By default, we are configured to use MEF /// </summary> protected override void Configure() { //to start we just add the already loaded assemblies to the container & the assemblies in exe folder var directoryCatalog = new DirectoryCatalog(@"./"); //use this code to look into loader exceptions, the code bellow is faster. //try //{ // // load the assembly or type // foreach (var part in directoryCatalog.Parts) // { // var assembly = ReflectionModelServices.GetPartType(part).Value.Assembly; // if (!AssemblySource.Instance.Contains(assembly)) // AssemblySource.Instance.Add(assembly); // } //} //catch (Exception ex) //{ // if (ex is System.Reflection.ReflectionTypeLoadException) // { // var typeLoadException = ex as ReflectionTypeLoadException; // var loaderExceptions = typeLoadException.LoaderExceptions; // } //} AssemblySource.Instance.AddRange( directoryCatalog.Parts .AsParallel() .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly) .ToList() .Where(assembly => !AssemblySource.Instance.Contains(assembly))); var catalog = new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x))); _container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddExportedValue <IWindowManager>(new WindowManager()); var eventAggregator = new EventAggregator(); batch.AddExportedValue <IEventAggregator>(eventAggregator); batch.AddExportedValue(new AssemblyLoader(_container, eventAggregator)); batch.AddExportedValue(_container); //batch.AddExportedValue(catalog); _container.Compose(batch); }
public override ICollection <Type> GetControllerTypes(IAssembliesResolver assembliesResolver) { var ret = base.GetControllerTypes(assembliesResolver); var parts = _container.Catalog.Parts.Where( partDef => partDef.ExportDefinitions.Any( p => string.Equals(p.ContractName, ContractNames.ApiController, StringComparison.Ordinal))); foreach (var composablePartDefinition in parts) { // TODO this isn't fantastic as it makes a lot of assumption about the CPD var lazyType = ReflectionModelServices.GetPartType(composablePartDefinition); ret.Add(lazyType.Value); } return(ret); }
private static Func <ComposablePartDefinition, bool> GetPartFilter(string configurationFilePath) { var config = GetContainerConfig(configurationFilePath); if (config?.ExcludedAssemblies == null || !config.ExcludedAssemblies.Any()) { return(part => true); } return(part => { var type = ReflectionModelServices.GetPartType(part).Value; var assemblyName = type.Assembly.GetName().Name; return !config.ExcludedAssemblies.ContainsIgnoreCase(assemblyName) || config.IncludedTypes.ContainsIgnoreCase(type.FullName); }); }
private static MultiDictionary <string, PluginInfo> LoadPlugins(List <string> assemblies) { var stopwatch = Stopwatch.StartNew(); var assemblyCatalogs = assemblies.Select(a => new AssemblyCatalog(a)); var container = new CompositionContainer(new AggregateCatalog(assemblyCatalogs)); var mefPlugins = container.Catalog.Parts .Select(part => new { PluginType = ReflectionModelServices.GetPartType(part).Value, part.ExportDefinitions }) .SelectMany(part => part.ExportDefinitions.Select(exportDefinition => new { exportDefinition.ContractName, exportDefinition.Metadata, part.PluginType })); var pluginsByExport = new MultiDictionary <string, PluginInfo>(); int pluginsCount = 0; foreach (var mefPlugin in mefPlugins) { pluginsCount++; pluginsByExport.Add( mefPlugin.ContractName, new PluginInfo { Type = mefPlugin.PluginType, Metadata = mefPlugin.Metadata.ToDictionary(m => m.Key, m => m.Value) }); } foreach (var pluginsGroup in pluginsByExport) { SortByDependency(pluginsGroup.Value); } InitializationLogging.PerformanceLogger.Write(stopwatch, "MefPluginScanner: Loaded plugins (" + pluginsCount + ")."); return(pluginsByExport); }
private void buttonCopy_Click(object sender, EventArgs e) { var pluginNames = _pluginHost.Container.Catalog.Parts .Select(x => ReflectionModelServices.GetPartType(x).Value.Assembly) .Distinct() .Select(x => $"{x.GetName().Name} @ {x.GetName().Version}") .ToArray(); var txt = $@"Generic Exchange Transport Agent @ {_version} Build: {_build} Revision {_revision} Loaded Plugins: {string.Join("\n", pluginNames)}"; Clipboard.SetText(txt, TextDataFormat.UnicodeText); buttonCopy.Text = "Copied!"; }
private static IEnumerable <Type> GetTypesFromCatalog(ComposablePartCatalog catalog) { if (catalog is AggregateCatalog) { return(((AggregateCatalog)catalog).Catalogs.SelectMany(c => GetTypesFromCatalog(c))); } else if (catalog is TypeCatalog || IsDeploymentCatalog(catalog)) { return(catalog.Parts.Select(p => ReflectionModelServices.GetPartType(p).Value)); } else if (catalog is AssemblyCatalog) { return(((AssemblyCatalog)catalog).Assembly.GetTypes()); } else { return(Enumerable.Empty <Type>()); } }
protected override IEnumerable <Assembly> SelectAssemblies() { m_DirectoryCatalog = new DirectoryCatalog(ConsolePath); m_Assemblies = m_DirectoryCatalog.Parts.Select(part => ReflectionModelServices.GetPartType(part) .Value.Assembly) .Distinct(); var assemblyNames = m_Assemblies.Select(a => a.ManifestModule.Name) .ToList(); var assemblyList = new List <Assembly> { Assembly.GetEntryAssembly() }; foreach (var assembly in assemblyNames) { assemblyList.Add(Assembly.LoadFrom(assembly)); } return(assemblyList); }
private Type GetTypeForPart(ComposablePartDefinition definition) { Type ret; if (_partToType.TryGetValue(definition, out ret)) { return(ret); } try { ret = ReflectionModelServices.GetPartType(definition).Value; } catch (ArgumentException) { // ReflectionModelServices.GetPartType throws an argument exception if the definition passed in isn't a reflection part ret = null; } _partToType[definition] = ret; return(ret); }
/// <summary> /// By default, we are configured to use MEF /// </summary> protected override void Configure() { var directoryCatalog = new DirectoryCatalog(@"./"); AssemblySource.Instance.AddRange( directoryCatalog.Parts .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly) .Where(assembly => !AssemblySource.Instance.Contains(assembly))); var catalog = new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x))); _container = new CompositionContainer(catalog); var batch = new CompositionBatch(); batch.AddExportedValue <IWindowManager>(new WindowManager()); batch.AddExportedValue <IEventAggregator>(new EventAggregator()); batch.AddExportedValue(_container); batch.AddExportedValue(catalog); _container.Compose(batch); }
static void Main() { var catalog = new AssemblyCatalog(typeof(Program).Assembly); var filteredCatalog = catalog.Filter(p => { var type = ReflectionModelServices.GetPartType(p).Value; return(typeof(IClass).IsAssignableFrom(type) && // implements interface you're looking for Attribute.IsDefined(type, typeof(ExportMetadataAttribute)) && // has ExportMetadata attribute // check for Type == MyClassType.TypeA type.GetCustomAttributes(typeof(ExportMetadataAttribute), true).Any(ca => { var ema = (ExportMetadataAttribute)ca; return ema.Name == "Type" && (MyClassType)ema.Value == MyClassType.TypeA; })); }); var container = new CompositionContainer(filteredCatalog); MyClassConsumer mcc = new MyClassConsumer(); container.ComposeParts(mcc); Console.WriteLine("Imported property's type: {0}", mcc.MyClass.GetType()); Console.ReadLine(); }
/// <summary> /// Gets the exported object described by the specified <see cref="T:System.ComponentModel.Composition.Primitives.ExportDefinition"/> object. /// </summary> /// <param name="definition">One of the <see cref="T:System.ComponentModel.Composition.Primitives.ExportDefinition"/> objects from the <see cref="P:System.ComponentModel.Composition.Primitives.ComposablePart.ExportDefinitions"/> property that describes the exported object to return.</param> /// <returns> /// The exported object described by <paramref name="definition"/>. /// </returns> /// <exception cref="T:System.ObjectDisposedException">The <see cref="T:System.ComponentModel.Composition.Primitives.ComposablePart"/> object has been disposed of.</exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="definition"/> is null.</exception> /// <exception cref="T:System.ComponentModel.Composition.Primitives.ComposablePartException">An error occurred getting the exported object described by the <see cref="T:System.ComponentModel.Composition.Primitives.ExportDefinition"/>.</exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="definition"/> did not originate from the <see cref="P:System.ComponentModel.Composition.Primitives.ComposablePart.ExportDefinitions"/> property on the <see cref="T:System.ComponentModel.Composition.Primitives.ComposablePart"/>.</exception> /// <exception cref="T:System.InvalidOperationException">One or more prerequisite imports, indicated by <see cref="P:System.ComponentModel.Composition.Primitives.ImportDefinition.IsPrerequisite"/>, have not been set.</exception> public override object GetExportedValue(ExportDefinition definition) { if (definition == null) { throw new ArgumentNullException("definition"); } if (this._values.ContainsKey(definition)) { return(this._values[definition]); } Lazy <Type> type = ReflectionModelServices.GetPartType(this._definition); string contractName = definition.ContractName; object partProxy = PartHostManager.CreateInstance(type.Value, this._isolationMetadata.ConfigFileBaseName, contractName); this._values[definition] = partProxy; return(partProxy); }
private void LoadPlugins() { var executionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (string.IsNullOrWhiteSpace(executionPath)) { return; } var pathToPlugins = Path.Combine(executionPath, PluginFolderName); if (!Directory.Exists(pathToPlugins)) { return; } var directoryCatalog = new DirectoryCatalog($".//{PluginFolderName}//"); AssemblySource.Instance.AddRange( directoryCatalog.Parts .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly) .Where(assembly => !AssemblySource.Instance.Contains(assembly))); }
public static ContractBasedImportDefinition ReadImportDefinition(ComposablePartDefinition owner, IDictionary <string, object> cache) { Assumes.NotNull(owner); Assumes.NotNull(cache); Lazy <Type> partType = ReflectionModelServices.GetPartType(owner); ICompositionElement origin = owner as ICompositionElement; if (cache.ReadValue <string>(AttributedCacheServices.CacheKeys.ImportType) == AttributedCacheServices.ImportTypes.Parameter) { return(ReflectionModelServices.CreateImportDefinition( cache.ReadLazyParameter(partType), cache.ReadContractName(), cache.ReadValue <string>(AttributedCacheServices.CacheKeys.RequiredTypeIdentity), cache.ReadRequiredMetadata(), cache.ReadValue <ImportCardinality>(AttributedCacheServices.CacheKeys.Cardinality, ImportCardinality.ExactlyOne), cache.ReadValue <CreationPolicy>(AttributedCacheServices.CacheKeys.RequiredCreationPolicy, CreationPolicy.Any), origin)); } else { LazyMemberInfo importingMemberInfo = new LazyMemberInfo( cache.ReadValue <MemberTypes>(AttributedCacheServices.CacheKeys.MemberType, MemberTypes.Property), cache.ReadLazyAccessors(partType)); return(ReflectionModelServices.CreateImportDefinition( importingMemberInfo, cache.ReadContractName(), cache.ReadValue <string>(AttributedCacheServices.CacheKeys.RequiredTypeIdentity), cache.ReadRequiredMetadata(), cache.ReadValue <ImportCardinality>(AttributedCacheServices.CacheKeys.Cardinality, ImportCardinality.ExactlyOne), cache.ReadValue <bool>(AttributedCacheServices.CacheKeys.IsRecomposable, false), cache.ReadValue <CreationPolicy>(AttributedCacheServices.CacheKeys.RequiredCreationPolicy, CreationPolicy.Any), origin)); } }
protected override void Configure() { DirectoryCatalog directoryCatalog = new DirectoryCatalog(@"./"); AssemblySource.Instance.AddRange( directoryCatalog.Parts.Select(p => ReflectionModelServices.GetPartType(p).Value.Assembly) ); AggregateCatalog catalog = new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType <ComposablePartCatalog>()); CatalogExportProvider provider = new CatalogExportProvider(catalog); Container = new CompositionContainer(new ApplicationCatalog()); provider.SourceProvider = Container; CompositionBatch batch = new CompositionBatch(); batch.AddExportedValue <IWindowManager>(new WindowManager()); batch.AddExportedValue <IEventAggregator>(new EventAggregator()); batch.AddExportedValue(Container); batch.AddExportedValue(catalog); batch.AddExportedValue(this); Container.Compose(batch); }
private static Func <ComposablePartDefinition, bool> GetPartFilter(string configurationFilePath) { var config = GetContainerConfig(configurationFilePath); if (config.ExcludedAssemblies.Count < 1 && config.ExcludedTypes.Count < 1) { return(part => true); } return(part => { var type = ReflectionModelServices.GetPartType(part).Value; var assemblyName = type.Assembly.GetName().Name; var typeName = type.FullName ?? string.Empty; if (typeName.Contains("`")) { typeName = typeName.Substring(0, typeName.IndexOf("`", StringComparison.InvariantCultureIgnoreCase)); } return (!config.ExcludedAssemblies.ContainsIgnoreCase(assemblyName) && !config.ExcludedTypes.ContainsIgnoreCase(typeName)) || config.IncludedTypes.ContainsIgnoreCase(typeName); }); }
/// <summary> /// Initializes a new instance of the <see cref="FilteredPart"/> class with the /// given part definition. /// </summary> public FilteredPart(ComposablePartDefinition part) { this.PartDefinition = part; this.PartType = ReflectionModelServices.GetPartType(part).Value; }