protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { List<Export> exports = new List<Export>(); ImportDefinition queryImport = TranslateImport(definition); if (queryImport == null) { return exports; } // go through the catalogs and see if there's anything there of interest foreach (CompositionScopeDefinition childCatalog in this._scopeDefinition.Children) { foreach (var partDefinitionAndExportDefinition in childCatalog.GetExportsFromPublicSurface(queryImport)) { using (var container = this.CreateChildContainer(childCatalog)) { // We create a nested AtomicComposition() because the container will be Disposed and // the RevertActions need to operate before we Dispose the child container using (var ac = new AtomicComposition(atomicComposition)) { var childCatalogExportProvider = container.CatalogExportProvider; if (!childCatalogExportProvider.DetermineRejection(partDefinitionAndExportDefinition.Item1, ac)) { exports.Add(this.CreateScopeExport(childCatalog, partDefinitionAndExportDefinition.Item1, partDefinitionAndExportDefinition.Item2)); } } } } } return exports; }
private void NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { // We invoke on the dispatcher because we are needing to recompose UI. // If we don't do this, an exception will be thrown as the composition isn't // guaranteed to happen on the necesary UI thread. Dispatcher.CurrentDispatcher.Invoke(new Action(() => { var oldStatus = _networkStatus; var newStatus = (e.IsAvailable) ? "Online" : "Offline"; var added = MatchingParts(newStatus); var removed = NonMatchingParts(newStatus); using (var atomic = new AtomicComposition()) { atomic.AddCompleteAction(() => _networkStatus = newStatus); if (Changing != null) { Changing(this, new ComposablePartCatalogChangeEventArgs(added, removed, atomic)); } atomic.Complete(); } if (Changed != null) { Changed(this, new ComposablePartCatalogChangeEventArgs(added, removed, null)); } })); }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition == null) throw new ArgumentNullException("definition"); if (SourceProvider == null) throw new InvalidOperationException("SourceProvider must be set."); var cbid = definition as ContractBasedImportDefinition; if (cbid == null || !cbid.RequiredTypeIdentity.StartsWith(PartCreatorContractPrefix)) return EmptyExports; var importInfo = _importDefinitionCache.GetOrCreate( cbid, () => new ExportFactoryImport(cbid)); var sourceExports = SourceProvider .GetExports(importInfo.ProductImport, atomicComposition); var result = sourceExports .Select(e => importInfo.CreateMatchingExport(e.Definition, SourceProvider)) .ToArray(); foreach (var e in sourceExports.OfType<IDisposable>()) e.Dispose(); return result; }
private void Recompose(IEnumerable<ComposablePartDefinition> added, IEnumerable<ComposablePartDefinition> removed, AtomicComposition outerComposition) { EnsurePartsInitialized(); var addedInnerPartDefinitions = added.Select(GetPart); var removedInnerPartDefinitions = removed.Select(def => innerParts[def]); using (var composition = new AtomicComposition(outerComposition)) { var addedDefinitions = addedInnerPartDefinitions.Select(p => p.Definition).ToList(); var removedDefinitions = removedInnerPartDefinitions.Select(p => p.Definition).ToList(); composition.AddCompleteAction(() => OnChanged( addedDefinitions, removedDefinitions, null)); OnChanging( addedDefinitions, removedDefinitions, composition); foreach (var innerPart in addedInnerPartDefinitions) { innerParts.Add(innerPart.Original, innerPart); } foreach (var removedDefinition in removedInnerPartDefinitions) { innerParts.Remove(removedDefinition.Original); } composition.Complete(); } }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.Cardinality != ImportCardinality.ExactlyOne) { return Enumerable.Empty<Export>(); } ExportSource exportSource; if (_exactlyOneExports.TryGetValue(definition.ContractName, out exportSource)) { AddMemberType(exportSource, definition); return new[] { exportSource.Export }; } string typeName = ImportDefinitionConstraintAnalyser.GetRequiredTypeIdentity(definition.Constraint); Type type = GetType(typeName); if (!CanHandleType(type)) { return Enumerable.Empty<Export>(); } exportSource = new ExportSource(definition.ContractName, definition.Metadata); exportSource.AddType(type); AddMemberType(exportSource, definition); _exactlyOneExports[definition.ContractName] = exportSource; return new[] { exportSource.Export }; }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var serviceTypeName = definition.ContractName; if (serviceTypeName.IndexOf('.') == -1 || serviceTypeName.StartsWith("System.") || serviceTypeName.StartsWith("Clide.")) return Enumerable.Empty<Export>(); return serviceExports.GetOrAdd (serviceTypeName, contractName => { var serviceType = typeMap.GetOrAdd(contractName, typeName => MapType(typeName)); if (serviceType == null) return Enumerable.Empty<Export>(); // NOTE: if we can retrieve a valid instance of the service at least once, we // assume we'll be able to retrieve it later on. Note also that we don't return // the single retrieved instance from the export, but rather provide a function // that does the GetService call every time, since we're caching the export but // we don't know if the service can be safely cached. var service = services.GetService(serviceType); if (service == null) return Enumerable.Empty<Export>(); return new Export[] { new Export(serviceTypeName, () => services.GetService(serviceType)) }; }); }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var contractName = definition.ContractName; if (contractName != SettingsConstants.SettingsContract) yield break; if (definition.Cardinality == ImportCardinality.ZeroOrMore) yield break; // TODO can't figure out how to get data injected into the Metadata collection //string settingsKey = definition.Metadata[SettingsConstants.SettingsMetadataKey] as string; LazyMemberInfo lazyMember = ReflectionModelServices.GetImportingMember(definition); MemberInfo member = lazyMember.GetAccessors().First(); MethodInfo getterOrSetter = (MethodInfo)member; // HACK this is pretty evil PropertyInfo propInfo = getterOrSetter.DeclaringType.GetProperty(getterOrSetter.Name.Substring(4)); ImportSettingAttribute settingsAttr = propInfo.GetCustomAttribute<ImportSettingAttribute>(); if (settingsAttr == null) yield break; object value; if (!this._settingsProvider.TryGetValue(settingsAttr.SettingsKey, out value)) yield break; yield return new Export(SettingsConstants.SettingsContract, () => value); }
/// <summary> /// Gets the available set of exports for the given import definition. /// </summary> /// <param name="definition">The defintion of the import.</param> /// <param name="atomicComposition">The atomic composition of the import.</param> /// <returns>The available set of exports for the given import definition.</returns> protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { Throw.IfArgumentNull(definition, "definition"); if (SourceProvider == null) Throw.InvalidOperation( string.Format( CultureInfo.CurrentUICulture, Resources.Exceptions.PropertyCannotBeNull, "Sourceprovider")); var contractDefinition = definition as ContractBasedImportDefinition; if (contractDefinition == null || !contractDefinition.RequiredTypeIdentity.StartsWith(PartFactoryContractPrefix)) return EmptyExports; var info = _definitionCache.Fetch(contractDefinition, () => new PartFactoryImport(contractDefinition)); var exports = SourceProvider.GetExports(info.ImportDefinition, atomicComposition); var result = exports .Select(e => info.CreateMatchingExport(e.Definition, SourceProvider)) .ToArray(); foreach (var export in exports.OfType<IDisposable>()) export.Dispose(); return result; }
protected override System.Collections.Generic.IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var type = Type.GetType(definition.ContractName); Export e; var exports = base.GetExportsCore(definition, atomicComposition); return exports; }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.ContractName.Equals(typeof(ILogger).FullName)) { yield return new Export(definition.ContractName, () => new Logger() { Header = "Factory - " }); } }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.ContractName == _textUndoHistoryRegistryContractName || definition.ContractName == _basicUndoHistoryRegistryContractName) { yield return _export; } }
public void Constructor2() { // Null should be allowed var ct = new AtomicComposition(null); // Another AtomicComposition should be allowed var ct2 = new AtomicComposition(ct); }
public void Constructor2_MultipleTimes() { var outer = new AtomicComposition(); var ct1 = new AtomicComposition(outer); ExceptionAssert.Throws<InvalidOperationException>(() => new AtomicComposition(outer)); }
protected override IEnumerable<Export> GetExportsCore( ImportDefinition definition, AtomicComposition atomicComposition ) { return from kv in _exports where definition.IsConstraintSatisfiedBy(kv.Key) select kv.Value; }
/// <summary> /// Invokes TryGetExports, returning the output as a collection. /// </summary> /// <param name="provider"></param> /// <param name="definition"></param> /// <param name="atomicComposition"></param> /// <returns></returns> public static IEnumerable<Export> TryGetExports(this ExportProvider provider, ImportDefinition definition, AtomicComposition atomicComposition) { Contract.Requires<ArgumentNullException>(provider != null); Contract.Requires<ArgumentNullException>(definition != null); IEnumerable<Export> exports; provider.TryGetExports(definition, atomicComposition, out exports); return exports; }
/// <summary> /// Returns all exports that match the constraint defined by the specified definition. /// </summary> /// <param name="definition">The <see cref="T:System.ComponentModel.Composition.Primitives.ImportDefinition"/> that defines the conditions of the /// <see cref="T:System.ComponentModel.Composition.Primitives.Export"/> objects to return.</param> /// <param name="atomicComposition"></param> /// <returns></returns> /// <result> /// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> of <see cref="T:System.ComponentModel.Composition.Primitives.Export"/> objects that match /// the conditions defined by <see cref="T:System.ComponentModel.Composition.Primitives.ImportDefinition"/>, if found; otherwise, an /// empty <see cref="T:System.Collections.Generic.IEnumerable`1"/>. /// </result> protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { List<Export> exports = new List<Export>(); if (_exportsDictionary.ContainsKey(definition.ContractName)) { exports.Add(_exportsDictionary[definition.ContractName]); } return exports; }
/// <summary> /// Initializes a new instance of the <see cref="ExportsChangeEventArgs"/> class with /// the specified changed export definitions. /// </summary> /// <param name="addedExports"> /// An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/>s of the exports /// that have been added. /// </param> /// <param name="removedExports"> /// An <see cref="IEnumerable{T}"/> of <see cref="ExportDefinition"/>s of the exports /// that have been removed. /// </param> /// <param name="atomicComposition"> /// A <see cref="AtomicComposition"/> representing all tentative changes that will /// be completed if the change is successful, or discarded if it is not. /// <see langword="null"/> if being applied outside a <see cref="AtomicComposition"/> /// or during a <see cref="ExportProvider.ExportsChanged"/> event. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="addedExports"/> or <paramref name="removedExports"/> is <see langword="null"/>. /// </exception> public ExportsChangeEventArgs(IEnumerable<ExportDefinition> addedExports, IEnumerable<ExportDefinition> removedExports, AtomicComposition atomicComposition) { Requires.NotNull(addedExports, "addedExports"); Requires.NotNull(removedExports, "removedExports"); this.AddedExports = addedExports.AsArray(); this.RemovedExports = removedExports.AsArray(); this.AtomicComposition = atomicComposition; }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (typeof(OliveOil).FullName != definition.ContractName) { return Enumerable.Empty<Export>(); } var export = new Export(definition.ContractName, () => new OliveOil()); return new[] { export }; }
/// <summary> /// Initializes a new instance of the <see cref="ComposablePartCatalogChangeEventArgs"/>. /// </summary> /// <param name="addedDefinitions"> /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that /// are being added to the <see cref="ComposablePartCatalog"/>. /// </param> /// <param name="removedDefinitions"> /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartDefinition"/> objects that /// are being removed from the <see cref="ComposablePartCatalog"/>. /// </param> /// <param name="atomicComposition"> /// A <see cref="AtomicComposition"/> representing all tentative changes that will /// be completed if the change is successful, or discarded if it is not. /// <see langword="null"/> if being applied outside a <see cref="AtomicComposition"/> /// or during a <see cref="INotifyComposablePartCatalogChanged.Changed"/> event. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="addedDefinitions"/> or <paramref name="removedDefinitions"/> is <see langword="null"/>. /// </exception> public ComposablePartCatalogChangeEventArgs(IEnumerable<ComposablePartDefinition> addedDefinitions, IEnumerable<ComposablePartDefinition> removedDefinitions, AtomicComposition atomicComposition) { Requires.NotNull(addedDefinitions, "addedDefinitions"); Requires.NotNull(removedDefinitions, "removedDefinitions"); this.AddedDefinitions = addedDefinitions.AsArray(); this.RemovedDefinitions = removedDefinitions.AsArray(); this.AtomicComposition = atomicComposition; }
public void SetValue_ToNull_ShouldBeAllowed() { var ct = new AtomicComposition(); ct.SetValue(ct, null); object value = new object(); Assert.IsTrue(ct.TryGetValue(ct, out value)); Assert.IsNull(value); }
public void SetValue_ValueType_ShouldBeAllowed() { var ct = new AtomicComposition(); ct.SetValue(ct, 45); int value; Assert.IsTrue(ct.TryGetValue(ct, out value)); Assert.AreEqual(45, value); }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { lock (this.Source) { foreach (Export e in this.GetConfigurationItems(definition) .GetExports<object>((t,s) => this.GetInstance(definition, t, s))) { yield return e; } } }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var contractName = definition.ContractName; if (string.IsNullOrEmpty(contractName)) { // no contract, nothing we can do yield break; } if (definition.Cardinality != ImportCardinality.ZeroOrOne && definition.Cardinality != ImportCardinality.ExactlyOne) { // we only support single value cardinalities yield break; } if (_source.Contains(contractName)) { // import was found to be an app setting - may need to convert it to an appropriate type for the importer Type targetType = null; string stringValue = null; if (ReflectionModelServices.IsImportingParameter(definition)) { // import appears on a parameter var importingParameter = ReflectionModelServices.GetImportingParameter(definition); targetType = importingParameter.Value.ParameterType; stringValue = _source.GetValue(contractName); } else { // import appears on a member (property) var getAccessor = ReflectionModelServices .GetImportingMember(definition) .GetAccessors() .Where(x => x is MethodInfo) .Select(x => x as MethodInfo) .FirstOrDefault(x => (x.Attributes & MethodAttributes.SpecialName) == MethodAttributes.SpecialName && x.Name.StartsWith("get_", StringComparison.Ordinal)); if (getAccessor == null) { // cannot determine type of importing property yield break; } targetType = getAccessor.ReturnType; stringValue = _source.GetValue(contractName); } var export = new Export(contractName, () => Convert.ChangeType(stringValue, targetType)); yield return export; } }
public void Dispose_AllMethodsShouldThrow() { var ct = new AtomicComposition(); ct.Dispose(); ExceptionAssert.ThrowsDisposed(ct, () => ct.AddCompleteAction(() => ct = null)); ExceptionAssert.ThrowsDisposed(ct, () => ct.Complete()); ExceptionAssert.ThrowsDisposed(ct, () => ct.SetValue(ct, 10)); object value; ExceptionAssert.ThrowsDisposed(ct, () => ct.TryGetValue(ct, out value)); }
public void AfterComplete_AllMethodsShouldThrow() { var ct = new AtomicComposition(); ct.Complete(); ExceptionAssert.Throws<InvalidOperationException>(() => ct.AddCompleteAction(() => ct = null)); ExceptionAssert.Throws<InvalidOperationException>(() => ct.Complete()); ExceptionAssert.Throws<InvalidOperationException>(() => ct.SetValue(ct, 10)); object value; ExceptionAssert.Throws<InvalidOperationException>(() => ct.TryGetValue(ct, out value)); }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.Cardinality == ImportCardinality.ZeroOrMore) { return from exportDefinition in this.ReadOnlyDefinitions let contractName = AttributedModelServices.GetContractName(exportDefinition.ContractType) where contractName == definition.ContractName select new Export(exportDefinition, () => exportDefinition.Factory(SourceProvider)); } return base.GetExportsCore(definition, atomicComposition); }
/// <summary> /// Previews all the required imports for the given <see cref="ComposablePart"/> to /// ensure they can all be satisified. The preview does not actually set the imports /// only ensures that they exist in the source provider. If the preview succeeds then /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source /// provider will not break any of the required imports. If this enforcement needs to be /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this /// <see cref="ComposablePart"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to preview the required imports. /// </param> /// <param name="atomicComposition"></param> /// <exception cref="CompositionException"> /// An error occurred during previewing and <paramref name="atomicComposition"/> is null. /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred. /// The pre-existing composition is in an unknown state, depending on the errors that occured. /// </exception> /// <exception cref="ChangeRejectedException"> /// An error occurred during the previewing and <paramref name="atomicComposition"/> is not null. /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred. /// The pre-existing composition remains in valid state. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ImportEngine"/> has been disposed of. /// </exception> public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition) { this.ThrowIfDisposed(); Requires.NotNull(part, "part"); // Do not do any previewing if SilentRejection is disabled. if (this._compositionOptions.HasFlag(CompositionOptions.DisableSilentRejection)) { return; } // NOTE : this is a very intricate area threading-wise, please use caution when changing, otherwise state corruption or deadlocks will ensue // The gist of what we are doing is as follows: // We need to lock the composition, as we will proceed modifying our internal state. The tricky part is when we release the lock // Due to the fact that some actions will take place AFTER we leave this method, we need to KEEP THAT LOCK HELD until the transation is commiited or rolled back // This is the reason we CAN'T use "using here. // Instead, if the transaction is present we will queue up the release of the lock, otherwise we will release it when we exit this method // We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless. // This will take the lock, if necesary IDisposable compositionLockHolder = this._lock.IsThreadSafe ? this._lock.LockComposition() : null; bool compositionLockTaken = (compositionLockHolder != null); try { // revert actions are processed in the reverse order, so we have to add the "release lock" action now if (compositionLockTaken && (atomicComposition != null)) { atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose()); } var partManager = GetPartManager(part, true); var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition); result.ThrowOnErrors(atomicComposition); StartSatisfyingImports(partManager, atomicComposition); // Add the "release lock" to the commit actions if (compositionLockTaken && (atomicComposition != null)) { atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose()); } } finally { // We haven't updated the queues, so we can release the lock now if (compositionLockTaken && (atomicComposition == null)) { compositionLockHolder.Dispose(); } } }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var exports = base.GetExportsCore(definition, atomicComposition); if ( definition.ContractName == typeof(IJsonConverter).FullName ) { object format; var r = from e in exports where e.Metadata.TryGetValue("Format", out format) && String.Equals(format, "Flat") select e; return r; } return exports; }
public static void DiscoverParts(AggregateCatalog catalog, IEnumerable<Assembly> assemblies) { using (var atomicComposition = new AtomicComposition()) { foreach (var assembly in assemblies) { System.Diagnostics.Debug.WriteLine(String.Format("{0}", assembly.FullName)); catalog.Catalogs.Add(new AssemblyCatalog(assembly)); } atomicComposition.Complete(); } }
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var baseExports = base.GetExportsCore(definition, atomicComposition).ToList(); Type typeToExport = null; //First, find the actual type that is being imported: There seems to be no way to retrieve the actual type that was used //during the export, so the only way we can find the type is to re-apply the 'logic' to create the contract name, based on a given type. foreach (var export in baseExports) { var valueType = export.Value.GetType(); typeToExport = GetMEFContractName(valueType) == definition.ContractName ? valueType : valueType.GetInterfaces().First(x => GetMEFContractName(x) == definition.ContractName); } //Convert all the export to a ForceFieldExport, which will create a Proxy when needed return baseExports.Select(export => new ForceFieldExport(_config, export, typeToExport)).ToList(); }
/// <summary> /// Returns the exports from the first provider that successfully returns exports. /// </summary> /// <param name="definition"></param> /// <param name="atomicComposition"></param> /// <returns></returns> protected virtual IEnumerable <Export> GetExportsCoreExactlyOne(ImportDefinition definition, AtomicComposition atomicComposition) { IEnumerable <Export> all = Enumerable.Empty <Export>(); foreach (var provider in providers) { // ask provider for exports IEnumerable <Export> exports; var got = provider.TryGetExports(definition, atomicComposition, out exports); var any = exports.Any(); // provider suceeded, and we have exports if (got && any) { return(exports); } // append exports to result if (any) { all = all.Concat(exports); } } return(all); }
/// <summary> /// Returns all of the provider's exports. /// </summary> /// <param name="definition"></param> /// <param name="atomicComposition"></param> /// <returns></returns> protected virtual IEnumerable <Export> GetExportsCoreZeroOrMore(ImportDefinition definition, AtomicComposition atomicComposition) { return(providers.SelectMany(i => i.TryGetExports(definition, atomicComposition))); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { return(GetExportsCoreInternal(definition, atomicComposition)); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var contractName = definition.ContractName; if (contractName == typeof(IOManager).FullName) { var mgr = new IOManager(FDeclarationFactory, IsInput); yield return(new Export(contractName, () => mgr)); } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.ContractName == _textUndoHistoryRegistryContractName || definition.ContractName == _basicUndoHistoryRegistryContractName) { yield return(_export); } }
/// <summary> /// GetExportsCore. /// </summary> /// <param name="importDefinition">importDefinition</param> /// <param name="atomicComposition">atomicComposition</param> /// <returns>Exports</returns> protected override IEnumerable<Export> GetExportsCore( ImportDefinition importDefinition, AtomicComposition atomicComposition) { return this.exports .Where(x => importDefinition.IsConstraintSatisfiedBy(x.Definition)); }
/// <summary> /// Retourne une collection de tous les exports qui correspondent aux conditions spécifiées dans l'<see cref="T:System.ComponentModel.Composition.Primitives.ImportDefinition"/>. /// </summary> /// <param name="definition">un objet définissant les conditions d'export</param> /// <param name="atomicComposition">La transaction de composition à utiliser.</param> /// <returns> /// Une collection des exports dans ce conteneur correspondant aux conditions de la définition. /// </returns> protected override IEnumerable <System.ComponentModel.Composition.Primitives.Export> GetExportsCore(System.ComponentModel.Composition.Primitives.ImportDefinition definition, AtomicComposition atomicComposition) { return(base.GetExportsCore(AdaptDefinition(definition), atomicComposition)); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { return(_inner.GetExports(definition, atomicComposition).Where(e => _filter(e.Definition))); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.ContractName.Equals(typeof(ILogger).FullName)) { yield return(new Export(definition.ContractName, () => new Logger() { Header = "Factory - " })); } }
/// <summary> /// Invokes TryGetExports, returning the output as a collection. /// </summary> /// <param name="provider"></param> /// <param name="definition"></param> /// <param name="atomicComposition"></param> /// <returns></returns> public static IEnumerable <Export> TryGetExports(this ExportProvider provider, ImportDefinition definition, AtomicComposition atomicComposition) { Debug.Assert(provider != null); Debug.Assert(definition != null); IEnumerable <Export> exports; provider.TryGetExports(definition, atomicComposition, out exports); return(exports); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var exports = _exportProvider.GetExports(definition, atomicComposition); return(exports.Select(export => new Export(export.Definition, () => GetValue(export)))); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { //var exports = base.GetExportsCore(definition, atomicComposition); var exports = base.GetExportsCore( new ImportDefinition( definition.Constraint, definition.ContractName, ImportCardinality.ZeroOrMore, definition.IsRecomposable, definition.IsPrerequisite, definition.Metadata ), atomicComposition); if (definition.Cardinality == ImportCardinality.ZeroOrMore) { return(exports); } //返回优先级最高的一个或者没有 return(exports.OrderByDescending(it => { object priority; if (it.Metadata.TryGetValue("Priority", out priority)) { return priority; } return 0; }).Take(1).ToArray()); }
/// <summary> /// Gets all the exports that match the constraint defined by the specified definition. /// </summary> /// <param name="definition">The object that defines the conditions of the /// System.ComponentModel.Composition.Primitives.Export objects to return.</param> /// <param name="atomicComposition">The transactional container for the composition.</param> /// <returns>A collection that contains all the exports that match the specified condition.</returns> protected override IEnumerable <Export> GetExportsCore( ImportDefinition definition, AtomicComposition atomicComposition) { var contractName = definition.ContractName; var nothingToDo = string.IsNullOrEmpty(contractName) || // no contract (definition.Cardinality != ImportCardinality.ZeroOrOne && definition.Cardinality != ImportCardinality.ExactlyOne); // we only support single value cardinalities if (nothingToDo) { yield break; } if (this.configurationSource.ContainsSetting(contractName)) { // import was found to be an app setting - may need to convert it to an appropriate type for the importer Type targetType = null; string stringValue = null; if (ReflectionModelServices.IsImportingParameter(definition)) { // import appears on a parameter var importingParameter = ReflectionModelServices.GetImportingParameter(definition); targetType = importingParameter.Value.ParameterType; stringValue = this.configurationSource.GetSetting(contractName); } else { // import appears on a member (property) var getAccessor = ReflectionModelServices .GetImportingMember(definition) .GetAccessors() .Where(x => x is MethodInfo) .Select(x => x as MethodInfo) .FirstOrDefault(x => (x.Attributes & MethodAttributes.SpecialName) == MethodAttributes.SpecialName && x.Name.StartsWith("get_", StringComparison.Ordinal)); if (getAccessor == null) { // cannot determine type of importing property yield break; } targetType = getAccessor.ReturnType; stringValue = this.configurationSource.GetSetting(contractName); } if (targetType == null) { yield break; } var export = new Export(contractName, () => Convert.ChangeType(stringValue, targetType)); yield return(export); } else if (this.configurationSource.ContainsSection(contractName)) { // import was found to be a configuration section var section = this.configurationSource.GetSection(contractName); yield return(new Export(contractName, () => section)); } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.ContractName == TypeFullName) { yield return(_export); } }
protected override IEnumerable <Export> GetExportsCoreExactlyOne(ImportDefinition definition, AtomicComposition atomicComposition) { // replace ZeroOrOne with ZeroOrMore to prevent errors down the chain; we'll grab the first var export = GetExportsCoreZeroOrMore(new ImportDefinition( definition.Constraint, definition.ContractName, ImportCardinality.ZeroOrMore, definition.IsRecomposable, definition.IsPrerequisite, definition.Metadata), atomicComposition) .FirstOrDefault(); if (export != null) { yield return(export); } if (definition.ContractName == AttributedModelServices.GetContractName(typeof(IFileSystemReader))) { yield return(new Export(definition.ContractName, () => new DefaultFileSystemReader())); } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition.Cardinality != ImportCardinality.ExactlyOne) { return(Enumerable.Empty <Export>()); } ExportSource exportSource; if (_exactlyOneExports.TryGetValue(definition.ContractName, out exportSource)) { AddMemberType(exportSource, definition); return(new[] { exportSource.Export }); } string typeName = ImportDefinitionConstraintAnalyser.GetRequiredTypeIdentity(definition.Constraint); Type type = GetType(typeName); if (!CanHandleType(type)) { return(Enumerable.Empty <Export>()); } exportSource = new ExportSource(definition.ContractName, definition.Metadata); exportSource.AddType(type); AddMemberType(exportSource, definition); _exactlyOneExports[definition.ContractName] = exportSource; return(new[] { exportSource.Export }); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { foreach (var keyValue in Extensions) { if (keyValue.Key.FullName == definition.ContractName) { foreach (var value in keyValue.Value) { yield return(new Export( new ExportDefinition(keyValue.Key.FullName, new Dictionary <string, object>()), () => value.Value )); } } } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { Export export; if (!FExports.TryGetValue(definition, out export)) { var contractName = definition.ContractName; if (contractName == typeof(IIOFactory).FullName) { export = new Export(contractName, () => FIOFactory); } else { var typeToExport = ExportProviderUtils.GetImportDefinitionType(definition); foreach (var attribute in ExportProviderUtils.GetImportDefinitionAttributes(definition)) { var ioAttribute = attribute as IOAttribute; if (ioAttribute == null) { continue; } if (!ReflectionModelServices.IsImportingParameter(definition)) { var member = ReflectionModelServices.GetImportingMember(definition); if (member.MemberType == MemberTypes.Property) { foreach (var accessor in member.GetAccessors()) { if (FAccessorToExportMap.TryGetValue(accessor, out export)) { break; } } } } if (export == null) { var context = IOBuildContext.Create(typeToExport, ioAttribute); if (FIOFactory.CanCreateIOContainer(context)) { export = new Export(contractName, () => FIOFactory.CreateIO(context)); // Now register the export for all the base members if (!ReflectionModelServices.IsImportingParameter(definition)) { var member = ReflectionModelServices.GetImportingMember(definition); if (member.MemberType == MemberTypes.Property) { foreach (var accessor in member.GetAccessors().OfType <MethodInfo>()) { RegisterExport(accessor, export); } } } } } if (export != null) { break; } } } FExports.Add(definition, export); } if (export != null) { yield return(export); } }
/// <summary> /// Initialises a new instance of <see cref="TaggedExportsChangeEventArgs" />. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="added">The set of added exports.</param> /// <param name="removed">The set of removed exports.</param> /// <param name="atomicComposition">The atomic composition of the exports.</param> public TaggedExportsChangeEventArgs(object sender, IEnumerable <ExportDefinition> added, IEnumerable <ExportDefinition> removed, AtomicComposition atomicComposition) : base(added, removed, atomicComposition) { Sender = sender; }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var contractName = definition.ContractName; if (contractName == typeof(ILogger).FullName) { var logger = new DefaultLogger(); logger.AddLogger(new PluginLogger(PluginHost)); yield return(new Export(contractName, () => logger)); } else if (contractName.StartsWith("VVVV.PluginInterfaces")) { var typeToExport = ExportProviderUtils.GetImportDefinitionType(definition); if (typeof(IPluginHost).IsAssignableFrom(typeToExport) || typeof(IPluginHost2).IsAssignableFrom(typeToExport) || typeof(INode).IsAssignableFrom(typeToExport)) { yield return(new Export(contractName, () => PluginHost)); yield break; } } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var baseExports = base.GetExportsCore(definition, atomicComposition).ToList(); Type typeToExport = null; //First, find the actual type that is being imported: There seems to be no way to retrieve the actual type that was used //during the export, so the only way we can find the type is to re-apply the 'logic' to create the contract name, based on a given type. foreach (var export in baseExports) { var valueType = export.Value.GetType(); typeToExport = GetMEFContractName(valueType) == definition.ContractName ? valueType : valueType.GetInterfaces().First(x => GetMEFContractName(x) == definition.ContractName); } //Convert all the export to a ForceFieldExport, which will create a Proxy when needed return(baseExports.Select(export => new ForceFieldExport(_config, export, typeToExport)).ToList()); }
/// <summary> /// 获取与指定约束相匹配的所有导出。 /// </summary> /// <param name="definition">定义要获取 <see cref="Export"/> 对象的条件对象。</param> /// <param name="atomicComposition">要使用的组合事务,或为 null 以禁用事务性组合。</param> /// <returns>与 <paramref name="definition"/> 相匹配的 <see cref="Export"/> 对象的集合。</returns> protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var exports = base.GetExportsCore(definition, atomicComposition); if (exports != null) { yield return(filterFunc(exports)); } }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { var exports = new List <Export>(); string implementingType; if (_mappings.TryGetValue(definition.ContractName, out implementingType)) { var t = Type.GetType(implementingType); if (t == null) { throw new InvalidOperationException("Type not found for interface: " + definition.ContractName); } var instance = t.GetConstructor(Type.EmptyTypes).Invoke(null); var exportDefintion = new ExportDefinition(definition.ContractName, new Dictionary <string, object>()); var toAdd = new Export(exportDefintion, () => instance); exports.Add(toAdd); } return(exports); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { return(from exportDefinition in this.definitions where definition.IsConstraintSatisfiedBy(exportDefinition) select new Export(exportDefinition, () => exportDefinition.Factory(SourceProvider))); }
protected override IEnumerable <Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition) { if (definition == null) { throw new ArgumentNullException("definition"); } if (SourceProvider == null) { throw new InvalidOperationException("SourceProvider must be set."); } var cbid = definition as ContractBasedImportDefinition; if (cbid == null || !cbid.RequiredTypeIdentity.StartsWith(PartCreatorContractPrefix)) { return(EmptyExports); } var importInfo = _importDefinitionCache.GetOrCreate( cbid, () => new PartCreatorImport(cbid)); var sourceExports = SourceProvider .GetExports(importInfo.ProductImport, atomicComposition); var result = sourceExports .Select(e => importInfo.CreateMatchingExport(e.Definition, SourceProvider)) .ToArray(); foreach (var e in sourceExports.OfType <IDisposable>()) { e.Dispose(); } return(result); }