private CompositionDependency(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site)
 {
     _target = target;
     _isPrerequisite = isPrerequisite;
     _site = site;
     _contract = contract;
 }
示例#2
0
 public void ChangingTheTypeOfAContractPreservesTheContractName()
 {
     var name = "a";
     var c = new CompositionContract(typeof(object), name);
     var d = c.ChangeType(typeof(AType));
     Assert.Equal(name, d.ContractName);
 }
        /// <summary>
        /// Promise export descriptors for the specified export key.
        /// </summary>
        /// <param name="contract">The export key required by another component.</param><param name="descriptorAccessor">Accesses the other export descriptors present in the composition.</param>
        /// <returns>
        /// Promises for new export descriptors.
        /// </returns>
        /// <remarks>
        /// A provider will only be queried once for each unique export key.
        ///             The descriptor accessor can only be queried immediately if the descriptor being promised is an adapter, such as
        ///             <see cref="T:System.Lazy`1"/>; otherwise, dependencies should only be queried within execution of the function provided
        ///             to the <see cref="T:System.Composition.Hosting.Core.ExportDescriptorPromise"/>. The actual descriptors provided should not close over or reference any
        ///             aspect of the dependency/promise structure, as this should be able to be GC'ed.
        /// </remarks>
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
        {
            var isSupported = this.servicesSupport.GetOrAdd(
                contract.ContractType,
                type => this.serviceProvider.GetService(type) != null);

            if (!isSupported)
            {
                return ExportDescriptorProvider.NoExportDescriptors;
            }

            return new[]
               {
                 new ExportDescriptorPromise(
                   contract,
                   contract.ContractType.Name,
                   true, // is shared
                   ExportDescriptorProvider.NoDependencies,
                   dependencies => ExportDescriptor.Create(
                     (c, o) =>
                       {
                       var instance = this.serviceProvider.GetService(contract.ContractType);
                       var disposable = instance as IDisposable;
                       if (disposable != null)
                       {
                         c.AddBoundInstance(disposable);
                       }

                       return instance;
                     }, 
                     ExportDescriptorProvider.NoMetadata))
               };
        }
        /// <summary>
        /// Construct a placeholder for a missing dependency. Note that this is different
        /// from an optional dependency - a missing dependency is an error.
        /// </summary>
        /// <param name="site">A marker used to identify the individual dependency among
        /// those on the dependent part.</param>
        /// <param name="contract">The contract required by the dependency.</param>
        public static CompositionDependency Missing(CompositionContract contract, object site)
        {
            Requires.NotNull(contract, nameof(contract));
            Requires.NotNull(site, nameof(site));

            return new CompositionDependency(contract, site);
        }
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
        {
            // Avoid trying to create defaults-of-defaults-of...
            if (contract.ContractName != null && contract.ContractName.StartsWith(Constants.DefaultContractNamePrefix))
                return NoExportDescriptors;

            var implementations = descriptorAccessor.ResolveDependencies("test for default", contract, false);
            if (implementations.Any())
                return NoExportDescriptors;

            var defaultImplementationDiscriminator = Constants.DefaultContractNamePrefix + (contract.ContractName ?? "");
            IDictionary<string, object> copiedConstraints = null;
            if (contract.MetadataConstraints != null)
                copiedConstraints = contract.MetadataConstraints.ToDictionary(k => k.Key, k => k.Value);
            var defaultImplementationContract = new CompositionContract(contract.ContractType, defaultImplementationDiscriminator, copiedConstraints);

            CompositionDependency defaultImplementation;
            if (!descriptorAccessor.TryResolveOptionalDependency("default", defaultImplementationContract, true, out defaultImplementation))
                return NoExportDescriptors;

            return new[]
            {
                new ExportDescriptorPromise(
                    contract,
                    "Default Implementation",
                    false,
                    () => new[] {defaultImplementation},
                    _ =>
                    {
                        var defaultDescriptor = defaultImplementation.Target.GetDescriptor();
                        return ExportDescriptor.Create((c, o) => defaultDescriptor.Activator(c, o), defaultDescriptor.Metadata);
                    })
            };
        }
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(
            CompositionContract contract,
            DependencyAccessor dependencyAccessor)
        {
            if (contract == null) throw new ArgumentNullException("contract");
            if (dependencyAccessor == null) throw new ArgumentNullException("dependencyAccessor");

            string key;
            CompositionContract unwrapped;

            if (!contract.TryUnwrapMetadataConstraint(SettingKey, out key, out unwrapped) ||
                !unwrapped.Equals(new CompositionContract(unwrapped.ContractType)) ||
                !SupportedSettingTypes.Contains(unwrapped.ContractType) ||
                !ConfigurationManager.AppSettings.AllKeys.Contains(key))
                yield break;

            var value = ConfigurationManager.AppSettings.Get(key);
            var converted = Convert.ChangeType(value, contract.ContractType);

            yield return new ExportDescriptorPromise(
                    contract,
                    "System.Configuration.ConfigurationManager.AppSettings",
                    true,
                    NoDependencies,
                    _ => ExportDescriptor.Create((c, o) => converted, NoMetadata));
        }
        public bool TryGetSingleForExport(CompositionContract exportKey, out ExportDescriptor defaultForExport)
        {
            ExportDescriptor[] allForExport;
            if (!_partDefinitions.TryGetValue(exportKey, out allForExport))
            {
                lock (_thisLock)
                {
                    if (!_partDefinitions.ContainsKey(exportKey))
                    {
                        var updatedDefinitions = new Dictionary<CompositionContract, ExportDescriptor[]>(_partDefinitions);
                        var updateOperation = new ExportDescriptorRegistryUpdate(updatedDefinitions, _exportDescriptorProviders);
                        updateOperation.Execute(exportKey);

                        _partDefinitions = updatedDefinitions;
                    }
                }

                allForExport = (ExportDescriptor[])_partDefinitions[exportKey];
            }

            if (allForExport.Length == 0)
            {
                defaultForExport = null;
                return false;
            }

            // This check is duplicated in the update process- the update operation will catch
            // cardinality violations in advance of this in all but a few very rare scenarios.
            if (allForExport.Length != 1)
                throw ThrowHelper.CardinalityMismatch_TooManyExports(exportKey.ToString());

            defaultForExport = allForExport[0];
            return true;
        }
        /// <summary>
        /// <see cref="ILogger"/>生成処理
        /// 
        /// https://mef.codeplex.com/wikipage?title=ProgrammingModelExtensions&referringTitle=Documentation
        /// </summary>
        /// <param name="contract"></param>
        /// <param name="descriptorAccessor"></param>
        /// <returns></returns>
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
        {
            if (contract.ContractType == typeof(ILogger))
            {
                string value = string.Empty;
                CompositionContract unwrap;

                contract.TryUnwrapMetadataConstraint("LogType", out value, out unwrap);

                string header = string.Format("[{0}] LogExportDescriptorProvider - ", value);

                return new ExportDescriptorPromise[]
                {
                    new ExportDescriptorPromise(
                        contract,
                        "ConsoleMef2 ILogger",
                        true,
                        NoDependencies,
                        _ => ExportDescriptor.Create((c, o) => new Logger() { Header = header },  NoMetadata)
                    )
                };
            }
            else
                return NoExportDescriptors;
        }
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
        {
            if (contract == null) throw new ArgumentNullException("contract");
            if (descriptorAccessor == null) throw new ArgumentNullException("descriptorAccessor");

            string name;
            CompositionContract unwrapped;

            var connectionStringSettings = ConfigurationManager.ConnectionStrings.OfType<ConnectionStringSettings>().ToArray();

            if (!contract.TryUnwrapMetadataConstraint(NameKey, out name, out unwrapped) ||
                !unwrapped.Equals(new CompositionContract(unwrapped.ContractType)) ||
                !(unwrapped.ContractType == typeof(string) || typeof(DbConnectionStringBuilder).IsAssignableFrom(unwrapped.ContractType)) ||
                !connectionStringSettings.Any(cs => cs.Name == name))
                yield break;

            var stringValue = connectionStringSettings.Single(cs => cs.Name == name).ConnectionString;
            object value = stringValue;

            if (contract.ContractType != typeof(string))
            {
                var stringBuilder = Activator.CreateInstance(contract.ContractType) as DbConnectionStringBuilder;
                if (stringBuilder == null) yield break;
                stringBuilder.ConnectionString = stringValue;
                value = stringBuilder;
            }

            yield return new ExportDescriptorPromise(
                    contract,
                    "System.Configuration.ConfigurationManager.ConnectionStrings",
                    true,
                    NoDependencies,
                    _ => ExportDescriptor.Create((c, o) => value, NoMetadata));
        }
示例#10
0
        /// <summary>
        /// Resolve a required dependency on exactly one implemenation of a contract.
        /// </summary>
        /// <param name="site">A tag describing the dependency site.</param>
        /// <param name="contract">The contract required by the site.</param>
        /// <param name="isPrerequisite">True if the dependency must be satisifed before corresponding exports can be retrieved; otherwise, false.</param>
        /// <returns>The dependency.</returns>
        public CompositionDependency ResolveRequiredDependency(object site, CompositionContract contract, bool isPrerequisite)
        {
            CompositionDependency result;
            if (!TryResolveOptionalDependency(site, contract, isPrerequisite, out result))
                return CompositionDependency.Missing(contract, site);

            return result;
        }
示例#11
0
 /// <summary>
 /// Resolve dependencies on all implementations of a contract.
 /// </summary>
 /// <param name="site">A tag describing the dependency site.</param>
 /// <param name="contract">The contract required by the site.</param>
 /// <param name="isPrerequisite">True if the dependency must be satisifed before corresponding exports can be retrieved; otherwise, false.</param>
 /// <returns>Dependencies for all implementations of the contact.</returns>
 public IEnumerable<CompositionDependency> ResolveDependencies(object site, CompositionContract contract, bool isPrerequisite)
 {
     var all = GetPromises(contract).ToArray();
     var result = new CompositionDependency[all.Length];
     for (var i = 0; i < all.Length; ++i)
         result[i] = CompositionDependency.Satisfied(contract, all[i], isPrerequisite, site);
     return result;
 }
        /// <summary>
        /// Construct a placeholder for an "exactly one" dependency that cannot be
        /// configured because multiple target implementations exist.
        /// </summary>
        /// <param name="site">A marker used to identify the individual dependency among
        /// those on the dependent part.</param>
        /// <param name="targets">The targets found when expecting only one.</param>
        /// <param name="contract">The contract required by the dependency.</param>
        public static CompositionDependency Oversupplied(CompositionContract contract, IEnumerable<ExportDescriptorPromise> targets, object site)
        {
            Requires.NotNull(targets, nameof(targets));
            Requires.NotNull(site, nameof(site));
            Requires.NotNull(contract, nameof(contract));

            return new CompositionDependency(contract, targets, site);
        }
        /// <summary>
        /// Construct a dependency on the specified target.
        /// </summary>
        /// <param name="target">The export descriptor promise from another part
        /// that this part is dependent on.</param>
        /// <param name="isPrerequisite">True if the dependency is a prerequisite
        /// that must be satisfied before any exports can be retrieved from the dependent
        /// part; otherwise, false.</param>
        /// <param name="site">A marker used to identify the individual dependency among
        /// those on the dependent part.</param>
        /// <param name="contract">The contract required by the dependency.</param>
        public static CompositionDependency Satisfied(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site)
        {
            Requires.NotNull(target, nameof(target));
            Requires.NotNull(site, nameof(site));
            Requires.NotNull(contract, nameof(contract));

            return new CompositionDependency(contract, target, isPrerequisite, site);
        }
		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors( CompositionContract contract, DependencyAccessor descriptorAccessor )
		{
			// var type = convention( contract.ContractType ) ?? contract.ContractType;
			contract.ContractType
					.Append( convention( contract.ContractType ) )
					.WhereAssigned()
					.Distinct()
					.Each( Initializer );
			yield break;
		}
            public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
            {
                if (!contract.Equals(_supportedContract))
                    return NoExportDescriptors;

                var implementations = descriptorAccessor.ResolveDependencies("test for existing", contract, false);
                if (implementations.Any())
                    return NoExportDescriptors;

                return new[] { new ExportDescriptorPromise(contract, "test metadataProvider", false, NoDependencies, _ => ExportDescriptor.Create((c, o) => DefaultObject, NoMetadata)) };
            }
        public void ConstraintsCanBeAppliedToGenerics()
        {
            var contract = new CompositionContract(typeof(SomeSetting<string>), null, new Dictionary<string, object>
            {
                { "SettingName", "TheName" }
            });

            var c = CreateContainer(typeof(SomeSetting<>));
            object s;
            Assert.True(c.TryGetExport(contract, out s));
        }
        public MefDependencyResolver(CompositionHost rootCompositionScope) : base(new Export<CompositionContext>(rootCompositionScope, rootCompositionScope.Dispose)) {

            if (rootCompositionScope == null) {
                throw new ArgumentNullException("rootCompositionScope");
            }

            var factoryContract = new CompositionContract(typeof(ExportFactory<CompositionContext>), null, new Dictionary<string, object> {
                { "SharingBoundaryNames", new[] { "HttpRequest" } }
            });

            this.RequestScopeFactory = (ExportFactory<CompositionContext>)rootCompositionScope.GetExport(factoryContract);
        }
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
        {
            if (!contract.Equals(s_currentScopeContract))
                return NoExportDescriptors;

            return new[] { new ExportDescriptorPromise(
                contract,
                typeof(CompositionContext).Name,
                true,
                NoDependencies,
                _ => ExportDescriptor.Create((c, o) => c, NoMetadata)) };
        }
 /// <summary>
 /// Create a promise for an export descriptor.
 /// </summary>
 /// <param name="origin">A description of where the export is being provided from (e.g. the part type).
 /// Used to provide friendly errors.</param>
 /// <param name="isShared">True if the export is shared within some context, otherwise false. Used in cycle
 /// checking.</param>
 /// <param name="dependencies">A function providing dependencies required in order to fulfill the promise.</param>
 /// <param name="getDescriptor">A function providing the promise.</param>
 /// <param name="contract">The contract fulfilled by this promise.</param>
 /// <seealso cref="ExportDescriptorProvider"/>.
 public ExportDescriptorPromise(
     CompositionContract contract,
     string origin,
     bool isShared,
     Func<IEnumerable<CompositionDependency>> dependencies,
     Func<IEnumerable<CompositionDependency>, ExportDescriptor> getDescriptor)
 {
     _contract = contract;
     _origin = origin;
     _isShared = isShared;
     _dependencies = new Lazy<ReadOnlyCollection<CompositionDependency>>(() => new ReadOnlyCollection<CompositionDependency>(dependencies().ToList()), false);
     _descriptor = new Lazy<ExportDescriptor>(() => getDescriptor(_dependencies.Value), false);
 }
        private void AddDiscoveredExport(DiscoveredExport export, CompositionContract contract = null)
        {
            var actualContract = contract ?? export.Contract;

            ICollection<DiscoveredExport> forKey;
            if (!_discoveredParts.TryGetValue(actualContract, out forKey))
            {
                forKey = new List<DiscoveredExport>();
                _discoveredParts.Add(actualContract, forKey);
            }

            forKey.Add(export);
        }
示例#21
0
 public ExportDescriptorPromise GetExportDescriptorPromise(
     CompositionContract contract,
     DependencyAccessor definitionAccessor)
 {
     return new ExportDescriptorPromise(
        contract,
        Part.PartType.Name,
        Part.IsShared,
        () => Part.GetDependencies(definitionAccessor),
        deps =>
        {
            var activator = Part.GetActivator(definitionAccessor, deps);
            return GetExportDescriptor(activator);
        });
 }
        protected bool IsSupportedContract(CompositionContract contract)
        {
            if (contract.ContractType != contractType || contract.ContractName != contractName)
                return false;

            if (contract.MetadataConstraints != null) {
                var subsetOfConstraints = contract.MetadataConstraints.Where(c => metadata.ContainsKey(c.Key)).ToDictionary(c => c.Key, c => metadata[c.Key]);
                var constrainedSubset = new CompositionContract(contract.ContractType, contract.ContractName,
                    subsetOfConstraints.Count == 0 ? null : subsetOfConstraints);

                if (!contract.Equals(constrainedSubset))
                    return false;
            }

            return true;
        }
        public StandaloneDependencyResolver(CompositionHost rootCompositionScope)
            : base(new Export<CompositionContext>(rootCompositionScope, rootCompositionScope.Dispose))
        {
            if (rootCompositionScope == null)
            {
                throw new ArgumentNullException(nameof(rootCompositionScope));
            }

            var metadataConstraints = new Dictionary<string, object>
            {
                { "SharingBoundaryNames", new[] { "HttpRequest" } }
            };

            var factoryContract = new CompositionContract(typeof(ExportFactory<CompositionContext>), contractName: null, metadataConstraints: metadataConstraints);

            this.requestScopeFactory = (ExportFactory<CompositionContext>)rootCompositionScope.GetExport(factoryContract);
        }
示例#24
0
        /// <summary>
        /// Resolve an optional dependency on exactly one implemenation of a contract.
        /// </summary>
        /// <param name="site">A tag describing the dependency site.</param>
        /// <param name="contract">The contract required by the site.</param>
        /// <param name="isPrerequisite">True if the dependency must be satisifed before corresponding exports can be retrieved; otherwise, false.</param>
        /// <param name="dependency">The dependency, or null.</param>
        /// <returns>True if the dependency could be resolved; otherwise, false.</returns>
        public bool TryResolveOptionalDependency(object site, CompositionContract contract, bool isPrerequisite, out CompositionDependency dependency)
        {
            var all = GetPromises(contract).ToArray();
            if (all.Length == 0)
            {
                dependency = null;
                return false;
            }

            if (all.Length != 1)
            {
                dependency = CompositionDependency.Oversupplied(contract, all, site);
                return true;
            }

            dependency = CompositionDependency.Satisfied(contract, all[0], isPrerequisite, site);
            return true;
        }
示例#25
0
        protected Host( Host existing )
            : base( existing )
        {
            Arg.NotNull( existing, nameof( existing ) );

            activityConfigurations = existing.activityConfigurations;
            activityTypes = existing.activityTypes;
            configSettingLocator = existing.configSettingLocator;
            configuration = existing.configuration;
            containerConfigurations = existing.containerConfigurations;
            conventionsHolder = existing.conventionsHolder;

            var boundaryNames = new Dictionary<string, object> { { "SharingBoundaryNames", new[] { Boundary.PerRequest } } };
            var contract = new CompositionContract( typeof( ExportFactory<CompositionContext> ), null, boundaryNames );
            var factory = (ExportFactory<CompositionContext>) existing.Container.GetExport( contract );

            container = new Lazy<CompositionContext>( () => factory.CreateExport().Value );
        }
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
        {
            DiscoverGenericParts(contract);
            DiscoverConstrainedParts(contract);

            ICollection<DiscoveredExport> forKey;
            if (!_discoveredParts.TryGetValue(contract, out forKey))
                return NoExportDescriptors;

            // Exports with metadata may be matched via metadata constraints.
            // It should be possible to do this more aggressively by changing the way
            // exports are stored.
            if (!forKey.Any(x => x.Metadata.Any()))
            {
                // Allow some garbage to be collected
                _discoveredParts.Remove(contract);
            }

            return forKey.Select(de => de.GetExportDescriptorPromise(contract, definitionAccessor)).ToArray();
        }
        /// <summary>
        /// Initialize the composition provider.
        /// </summary>
        /// <param name="applicationContext">A container supplying composed parts.</param>
        public static void Initialize(CompositionContext applicationContext)
        {
            if (applicationContext == null) throw new ArgumentNullException("applicationContext");

            lock (_initLock)
            {
                if (_applicationContext != null) throw new InvalidOperationException("Composition provider is already initialized.");
                _applicationContext = applicationContext;
            }

            var rcfContract = new CompositionContract(
                typeof(ExportFactory<CompositionContext>),
                null,
                new Dictionary<string, object> {
                    { "SharingBoundaryNames", new[] { Boundaries.HttpContext, Boundaries.DataConsistency, Boundaries.UserIdentity }}
            });

            _requestContextFactory = (ExportFactory<CompositionContext>)_applicationContext.GetExport(rcfContract);

            DependencyResolver.SetResolver(new ComposedDependencyResolver());
        }
示例#28
0
        private IEnumerable<DiscoveredExport> DiscoverInstanceExports(TypeInfo partType)
        {
            var partTypeAsType = partType.AsType();
            foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, partType))
            {
                IDictionary<string, object> metadata = new Dictionary<string, object>();
                ReadMetadataAttribute(export, metadata);

                var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, partType);
                ReadLooseMetadata(applied, metadata);

                var contractType = export.ContractType ?? partTypeAsType;
                CheckInstanceExportCompatibility(partType, contractType.GetTypeInfo());

                var exportKey = new CompositionContract(contractType, export.ContractName);

                if (metadata.Count == 0)
                    metadata = s_noMetadata;

                yield return new DiscoveredInstanceExport(exportKey, metadata);
            }
        }
        public void Execute(CompositionContract contract)
        {
            // Opportunism - we'll miss recursive calls to Execute(), but this will catch some problems
            // and the _updateFinished flag is required for other purposes anyway.
            if (_updateFinished) throw new InvalidOperationException("The update has already executed.");

            CompositionDependency initial;
            if (TryResolveOptionalDependency("initial request", contract, true, out initial))
            {
                var @checked = new HashSet<ExportDescriptorPromise>();
                var checking = new Stack<CompositionDependency>();
                CheckTarget(initial, @checked, checking);
            }

            _updateFinished = true;

            foreach (var result in _updateResults)
            {
                var resultContract = result.Key;
                var descriptors = result.Value.GetResults().Select(cb => cb.GetDescriptor()).ToArray();
                _partDefinitions.Add(resultContract, descriptors);
            }
        }
        // If the contract has metadata constraints, look for exports with matching metadata.
        private void DiscoverConstrainedParts(CompositionContract contract)
        {
            if (contract.MetadataConstraints != null)
            {
                var unconstrained = new CompositionContract(contract.ContractType, contract.ContractName);
                DiscoverGenericParts(unconstrained);

                ICollection<DiscoveredExport> forKey;
                if (_discoveredParts.TryGetValue(unconstrained, out forKey))
                {
                    foreach (var export in forKey)
                    {
                        var subsettedConstraints = contract.MetadataConstraints.Where(c => export.Metadata.ContainsKey(c.Key)).ToDictionary(c => c.Key, c => export.Metadata[c.Key]);
                        if (subsettedConstraints.Count != 0)
                        {
                            var constrainedSubset = new CompositionContract(unconstrained.ContractType, unconstrained.ContractName, subsettedConstraints);

                            if (constrainedSubset.Equals(contract))
                                AddDiscoveredExport(export, contract);
                        }
                    }
                }
            }
        }
        public void Missing_NullSite_ThrowsArgumentNullException()
        {
            var contract = new CompositionContract(typeof(int));

            AssertExtensions.Throws <ArgumentNullException>("site", () => CompositionDependency.Missing(contract, null));
        }
        public void Satisfied_NullTarget_ThrowsArgumentNullException()
        {
            var contract = new CompositionContract(typeof(int));

            AssertExtensions.Throws <ArgumentNullException>("target", () => CompositionDependency.Satisfied(contract, null, false, new object()));
        }
 public DiscoveredInstanceExport(CompositionContract contract, IDictionary <string, object> metadata)
     : base(contract, metadata)
 {
 }
        private static ExportDescriptorPromise GetImportManyDescriptor <TElement>(CompositionContract importManyContract, CompositionContract elementContract, DependencyAccessor definitionAccessor)
        {
            return(new ExportDescriptorPromise(
                       importManyContract,
                       typeof(TElement[]).Name,
                       false,
                       () => definitionAccessor.ResolveDependencies("item", elementContract, true),
                       d =>
            {
                var dependentDescriptors = d
                                           .Select(el => el.Target.GetDescriptor())
                                           .ToArray();

                return ExportDescriptor.Create((c, o) => dependentDescriptors.Select(e => (TElement)e.Activator(c, o)).ToArray(), NoMetadata);
            }));
        }
示例#35
0
 /// <summary>
 /// Retrieve the single <paramref name="contract"/> instance from the
 /// <see cref="CompositionContext"/>.
 /// </summary>
 /// <param name="contract">The contract to retrieve.</param>
 /// <returns>An instance of the export.</returns>
 /// <param name="export">The export if available, otherwise, null.</param>
 /// <exception cref="CompositionFailedException" />
 public abstract bool TryGetExport(CompositionContract contract, out object export);
        public void Oversupplied_NullTargets_ThrowsArgumentNullException()
        {
            var contract = new CompositionContract(typeof(int));

            AssertExtensions.Throws <ArgumentNullException>("targets", () => CompositionDependency.Oversupplied(contract, null, new object()));
        }
示例#37
0
        static ExportDescriptorPromise[] GetExportFactoryDescriptors <TProduct, TMetadata>(CompositionContract exportFactoryContract, DependencyAccessor definitionAccessor)
        {
            var productContract = exportFactoryContract.ChangeType(typeof(TProduct));
            var boundaries      = new string[0];

            IEnumerable <string> specifiedBoundaries;
            CompositionContract  unwrapped;

            if (exportFactoryContract.TryUnwrapMetadataConstraint(Constants.SharingBoundaryImportMetadataConstraintName, out specifiedBoundaries, out unwrapped))
            {
                productContract = unwrapped.ChangeType(typeof(TProduct));
                boundaries      = (specifiedBoundaries ?? new string[0]).ToArray();
            }

            var metadataProvider = MetadataViewProvider.GetMetadataViewProvider <TMetadata>();

            return(definitionAccessor.ResolveDependencies("product", productContract, false)
                   .Select(d => new ExportDescriptorPromise(
                               exportFactoryContract,
                               typeof(ExportFactory <TProduct, TMetadata>).Name,
                               false,
                               () => new[] { d },
                               _ =>
            {
                var dsc = d.Target.GetDescriptor();
                return ExportDescriptor.Create((c, o) =>
                {
                    return new ExportFactory <TProduct, TMetadata>(() =>
                    {
                        var lifetimeContext = new LifetimeContext(c, boundaries);
                        return Tuple.Create <TProduct, Action>((TProduct)CompositionOperation.Run(lifetimeContext, dsc.Activator), lifetimeContext.Dispose);
                    },
                                                                   metadataProvider(dsc.Metadata));
                },
                                               dsc.Metadata);
            }))
                   .ToArray());
        }
 public override IEnumerable <ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
 {
     throw new NotImplementedException();
 }
 public override IEnumerable <ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
 {
     CalledGetExportDescriptors++;
     return(new[]
     {
         new ExportDescriptorPromise(contract, "origin", false, () => new CompositionDependency[0], dependencies => ExportDescriptor.Create(CompositeActivator, new Dictionary <string, object>()))
     });
 }
示例#40
0
            public override IEnumerable <ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
            {
                if (!contract.Equals(_supportedContract))
                {
                    return(NoExportDescriptors);
                }

                var implementations = descriptorAccessor.ResolveDependencies("test for existing", contract, false);

                if (implementations.Any())
                {
                    return(NoExportDescriptors);
                }

                return(new[] { new ExportDescriptorPromise(contract, "test metadataProvider", false, NoDependencies, _ => ExportDescriptor.Create((c, o) => DefaultObject, NoMetadata)) });
            }
        public void Oversupplied_NullSite_ThrowsArgumentNullException()
        {
            var contract = new CompositionContract(typeof(int));

            AssertExtensions.Throws <ArgumentNullException>("site", () => CompositionDependency.Oversupplied(contract, Enumerable.Empty <ExportDescriptorPromise>(), null));
        }
示例#42
0
 /// <summary>
 /// Retrieve the single <paramref name="contract"/> instance from the
 /// <see cref="CompositionContext"/>.
 /// </summary>
 /// <param name="contract">The contract to retrieve.</param>
 /// <returns>An instance of the export.</returns>
 /// <param name="export">The export if available, otherwise, null.</param>
 /// <exception cref="CompositionFailedException" />
 public override bool TryGetExport(CompositionContract contract, out object export)
 {
     return(_rootLifetimeContext.TryGetExport(contract, out export));
 }
示例#43
0
 public DiscoveredPropertyExport(CompositionContract contract, IDictionary <string, object> metadata, PropertyInfo property)
     : base(contract, metadata)
 {
     _property = property;
 }
示例#44
0
 public ImportInfo(CompositionContract exportKey, bool allowDefault)
 {
     _exportKey    = exportKey;
     _allowDefault = allowDefault;
 }
        private static ExportDescriptorPromise[] GetLazyDefinitions <TValue, TMetadata>(CompositionContract lazyContract, DependencyAccessor definitionAccessor)
        {
            var metadataProvider = MetadataViewProvider.GetMetadataViewProvider <TMetadata>();

            return(definitionAccessor.ResolveDependencies("value", lazyContract.ChangeType(typeof(TValue)), false)
                   .Select(d => new ExportDescriptorPromise(
                               lazyContract,
                               Formatters.Format(typeof(Lazy <TValue, TMetadata>)),
                               false,
                               () => new[] { d },
                               _ =>
            {
                var dsc = d.Target.GetDescriptor();
                var da = dsc.Activator;
                return ExportDescriptor.Create((c, o) =>
                {
                    return new Lazy <TValue, TMetadata>(() => (TValue)CompositionOperation.Run(c, da), metadataProvider(dsc.Metadata));
                }, dsc.Metadata);
            }))
                   .ToArray());
        }
        // The source will only be asked for parts once per exportKey, but it is the
        // source's responsibility to return the same part multiple times when that part
        // has more than one export (not shown here.)
        //
        public override IEnumerable <ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
        {
            if (contract.Equals(new CompositionContract(typeof(RequestListener))))
            {
                return new[] { RequestListenerPart(contract, definitionAccessor) }
            }
            ;

            if (contract.Equals(new CompositionContract(typeof(ConsoleLog))))
            {
                return new[] { ConsoleLogPart(contract, definitionAccessor) }
            }
            ;

            return(NoExportDescriptors);
        }

        // Console log is a disposable singleton (no boundaries)
        // that exports itself under its own concrete type.
        //
        ExportDescriptorPromise ConsoleLogPart(CompositionContract contract, DependencyAccessor definitionAccessor)
        {
            return(new ExportDescriptorPromise(
                       contract,
                       typeof(ConsoleLog).Name,
                       true,
                       NoDependencies,
                       _ =>
            {
                var sharingId = LifetimeContext.AllocateSharingId();

                return ExportDescriptor.Create((c, o) =>
                {
                    CompositeActivator activatorBody = (sc, so) =>
                    {
                        var result = new ConsoleLog();
                        c.AddBoundInstance(result);
                        return result;
                    };

                    var scope = c.FindContextWithin(null);
                    if (object.ReferenceEquals(scope, c))
                    {
                        return scope.GetOrCreate(sharingId, o, activatorBody);
                    }
                    else
                    {
                        return CompositionOperation.Run(scope, (c1, o1) => c1.GetOrCreate(sharingId, o1, activatorBody));
                    }
                }, NoMetadata);
            }));
        }

        // Non-shared part that exports itself and has a dependency on ConsoleLog.
        //
        ExportDescriptorPromise RequestListenerPart(CompositionContract contract, DependencyAccessor definitionAccessor)
        {
            return(new ExportDescriptorPromise(
                       contract,
                       typeof(RequestListener).Name,
                       false,
                       () => new[] { definitionAccessor.ResolveRequiredDependency("log", new CompositionContract(typeof(Lazy <ConsoleLog>)), true) },
                       dependencies =>
            {
                var logActivator = dependencies.Single().Target.GetDescriptor().Activator;
                return ExportDescriptor.Create((c, o) =>
                {
                    var log = (Lazy <ConsoleLog>)logActivator(c, o);
                    return new RequestListener(log);
                }, NoMetadata);
            }));
        }
    }
}