public static IDictionary<string, object> WriteImportDefinition(ComposablePartDefinition owner, ContractBasedImportDefinition importDefinition)
        {
            Assumes.NotNull(owner);
            Assumes.NotNull(importDefinition);

            Lazy<Type> partType = ReflectionModelServices.GetPartType(owner);

            IDictionary<string, object> cache = new Dictionary<string, object>();
            cache.WriteContractName(importDefinition.ContractName);
            cache.WriteValue(AttributedCacheServices.CacheKeys.RequiredTypeIdentity, importDefinition.RequiredTypeIdentity, null);
            cache.WriteRequiredMetadata(importDefinition.RequiredMetadata);
            cache.WriteValue(AttributedCacheServices.CacheKeys.RequiredCreationPolicy, importDefinition.RequiredCreationPolicy, CreationPolicy.Any);
            cache.WriteValue(AttributedCacheServices.CacheKeys.Cardinality, importDefinition.Cardinality, ImportCardinality.ExactlyOne);
            if (ReflectionModelServices.IsImportingParameter(importDefinition))
            {
                cache.WriteValue(AttributedCacheServices.CacheKeys.ImportType, AttributedCacheServices.ImportTypes.Parameter);
                cache.WriteLazyParameter(
                        ReflectionModelServices.GetImportingParameter(importDefinition),
                        partType);
            }
            else
            {
                // don't write anything for import type - member assumed
                LazyMemberInfo importingMemberInfo = ReflectionModelServices.GetImportingMember(importDefinition);
                cache.WriteValue(AttributedCacheServices.CacheKeys.IsRecomposable, importDefinition.IsRecomposable, false);
                cache.WriteValue(AttributedCacheServices.CacheKeys.MemberType, importingMemberInfo.MemberType , MemberTypes.Property);
                cache.WriteLazyAccessors(
                        importingMemberInfo.GetAccessors(),
                        partType);
            }

            return cache;
        }
Exemplo n.º 2
0
        public ImportingMember(ContractBasedImportDefinition definition, ReflectionWritableMember member, ImportType importType)
            : base(definition, importType)
        {
            Assumes.NotNull(definition, member);

            this._member = member;
        }
Exemplo n.º 3
0
        protected ImportingItem(ContractBasedImportDefinition definition, ImportType importType)
        {
            Assumes.NotNull(definition);

            this._definition = definition;
            this._importType = importType;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets teh ViewModel export 
        /// </summary>
        /// <param name="vmContractName">The contract for the view model to get</param>
        /// <returns></returns>
        public Export GetViewModelByContract(string vmContractName)
        {
            if (_container == null)
            {
                // try getting the container again
                _container = LocatorBootstrapper.EnsureLocatorBootstrapper();
            }

            var viewModelTypeIdentity = AttributedModelServices.GetTypeIdentity(typeof(object));
            var requiredMetadata = new Dictionary<string, Type>();
            requiredMetadata[ExportViewModel.NameProperty] = typeof(string);
            requiredMetadata[ExportViewModel.ContextAwareServicesProperty] = typeof(IEnumerable<Type>);
            requiredMetadata[ExportViewModel.IsDataContextAwareProperty] = typeof(bool);


            var definition = new ContractBasedImportDefinition(ExportViewModel.Contract, viewModelTypeIdentity,
                                                               requiredMetadata, ImportCardinality.ZeroOrMore, false,
                                                               false, CreationPolicy.NonShared);

            var vmExports = _container.GetExports(definition);
            var vmExport = vmExports.Single(e => e.Metadata[ExportViewModel.NameProperty].Equals(vmContractName));
            if (vmExport != null)
                return vmExport;
            return null;
        }
Exemplo n.º 5
0
        private static ImportDefinition TranslateImport(ImportDefinition import, ComposablePartDefinition part)
        {
            ContractBasedImportDefinition contractBasedImport = import as ContractBasedImportDefinition;

            if (contractBasedImport == null)
            {
                return(import);
            }

            int[] importParametersOrder = contractBasedImport.Metadata.GetValue <int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
            if (importParametersOrder == null)
            {
                return(import);
            }

            int partArity = part.Metadata.GetValue <int>(CompositionConstants.GenericPartArityMetadataName);

            if (partArity == 0)
            {
                return(import);
            }

            string contractName         = GenericServices.GetGenericName(contractBasedImport.ContractName, importParametersOrder, partArity);
            string requiredTypeIdentity = GenericServices.GetGenericName(contractBasedImport.RequiredTypeIdentity, importParametersOrder, partArity);

            return(new ContractBasedImportDefinition(
                       contractName,
                       requiredTypeIdentity,
                       contractBasedImport.RequiredMetadata,
                       contractBasedImport.Cardinality,
                       contractBasedImport.IsRecomposable,
                       false,
                       contractBasedImport.RequiredCreationPolicy,
                       contractBasedImport.Metadata));
        }
 public object GetInstance(Type serviceType, InstanceContext instanceContext, Message message)
 {
     var contract = AttributedModelServices.GetContractName(serviceType);
     var identity = AttributedModelServices.GetTypeIdentity(serviceType);
     var definition = new ContractBasedImportDefinition(contract, identity, null, ImportCardinality.ExactlyOne, false,
                                                         false, CreationPolicy.NonShared);
     return _container.GetExports(definition).First().Value;
 }
Exemplo n.º 7
0
        // Get the instance from MEF
        public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage message)
        {
            var contract = AttributedModelServices.GetContractName(serviceType);
            var identity = AttributedModelServices.GetTypeIdentity(serviceType);

            // force non-shared so that every service doesn't need to have a [PartCreationPolicy] attribute.
            var definition = new ContractBasedImportDefinition(contract, identity, null, ImportCardinality.ExactlyOne, false, false, CreationPolicy.NonShared);
            return this.container.GetExports(definition).First().Value;
        }
 public PartCreatorMemberImportDefinition(
     LazyMemberInfo importingLazyMember,
     ICompositionElement origin,
     ContractBasedImportDefinition productImportDefinition)
     : base(importingLazyMember, CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity,
         productImportDefinition.RequiredMetadata, productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, CreationPolicy.Any, origin)
 {
     Assumes.NotNull(productImportDefinition);
     this._productImportDefinition = productImportDefinition;
 }
 /// <summary>
 /// Create an UnsuitableExportDefinitionInfo.
 /// </summary>
 /// <param name="target">Import for which the export is unsuitable.</param>
 /// <param name="exportDefinition">Unsuitable export.</param>
 /// <param name="partDefinition">Part definition that provided the export.</param>
 public UnsuitableExportDefinitionInfo(
     ContractBasedImportDefinition target,
     ExportDefinition exportDefinition,
     PartDefinitionInfo partDefinition)
 {
     ExportDefinition = exportDefinition;
     PartDefinition = partDefinition;
     _issues = CheckForRequiredMetadataIssues(target, exportDefinition)
                     .Concat(CheckForTypeIdentityIssues(target, exportDefinition))
                     .Concat(CheckForCreationPolicyIssues(target, partDefinition.PartDefinition))
                     .ToArray();
 }
Exemplo n.º 10
0
        public static bool ShouldCreateClosedGenericPart(ContractBasedImportDefinition definition, Type importDefinitionType)
        {
            if (definition == null)
            {
                throw new ArgumentNullException("definition");
            }

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

            return definition.Cardinality != ImportCardinality.ZeroOrMore && importDefinitionType.IsGenericType;
        }
Exemplo n.º 11
0
        public static IEnumerable<object> GetExportedValuesByType(this CompositionContainer container, Type type)
        {
            foreach (var PartDef in container.Catalog.Parts)
            {
                foreach (var ExportDef in PartDef.ExportDefinitions)
                {
                    if (ExportDef.ContractName == type.FullName)
                    {
                        var contract = AttributedModelServices.GetContractName(type);
                        var definition = new ContractBasedImportDefinition(contract, contract, null, ImportCardinality.ExactlyOne,
                                                                            false, false, CreationPolicy.Any);
                        return container.GetExports(definition);
                    }
                }
            }

            return new List<object>();
        }
Exemplo n.º 12
0
        public Export GetServiceByContract(Type serviceType)
        {
            if (_container == null)
            {
                // try getting the container again
                _container = LocatorBootstrapper.EnsureLocatorBootstrapper();
            }

            var serviceTypeIdentity = AttributedModelServices.GetTypeIdentity(serviceType);
            var requiredMetadata = new Dictionary<string, Type>();
            requiredMetadata[ExportService.IsDesignTimeServiceProperty] = typeof(ServiceType);
            requiredMetadata[ExportService.ServiceContractProperty] = typeof(Type);


            var definition = new ContractBasedImportDefinition(serviceTypeIdentity, serviceTypeIdentity,
                                                               requiredMetadata, ImportCardinality.ZeroOrMore, false,
                                                               false, CreationPolicy.NonShared);

            var vmExport = _container.GetExports(definition).FirstOrDefault();
            if (vmExport != null)
                return vmExport;
            return null;
        }
 static IEnumerable<UnsuitableExportDefinitionIssue> CheckForCreationPolicyIssues(ContractBasedImportDefinition cbid, ComposablePartDefinition pd)
 {
     if (cbid.RequiredCreationPolicy != CreationPolicy.Any)
     {
         object actual;
         if (pd.Metadata.TryGetValue(CompositionConstants.PartCreationPolicyMetadataName, out actual) &&
             actual != null)
         {
             if (actual is CreationPolicy && !actual.Equals(cbid.RequiredCreationPolicy))
             {
                 yield return new UnsuitableExportDefinitionIssue(
                     UnsuitableExportDefinitionReason.CreationPolicy,
                     string.Format("The import requires creation policy '{0}', but the exporting part only supports '{1}'.",
                         cbid.RequiredCreationPolicy, actual));
             }
             else
             {
                 yield return new UnsuitableExportDefinitionIssue(
                     UnsuitableExportDefinitionReason.CreationPolicy,
                     string.Format("The metadata stored for creation policy should be of type CreationPolicy, but is '{0}'.", actual.GetType()));
             }
         }
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Gets teh ViewModel export 
        /// </summary>
        /// <param name="vmContractName">The contract for the view model to get</param>
        /// <returns></returns>
        public Export GetViewModelByContract(string vmContractName, object contextToInject)
        {
            if(Container == null)
                return null;

            var viewModelTypeIdentity = AttributedModelServices.GetTypeIdentity(typeof(object));
            var requiredMetadata = new Dictionary<string, Type>();
            requiredMetadata[ExportViewModel.NameProperty] = typeof(string);
            requiredMetadata[ExportViewModel.IsDataContextAwareProperty] = typeof(bool);


            var definition = new ContractBasedImportDefinition(vmContractName, viewModelTypeIdentity,
                                                               requiredMetadata, ImportCardinality.ZeroOrMore, false,
                                                               false, CreationPolicy.Any);

            SetContextToExportProvider(contextToInject);
            var vmExports = Container.GetExports(definition);
            SetContextToExportProvider(null);

            var vmExport = vmExports.FirstOrDefault(e => e.Metadata[ExportViewModel.NameProperty].Equals(vmContractName));
            if (vmExport != null)
                return vmExport;
            return null;
        }
 private IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ContractBasedImportDefinition definition)
 {
     ComposablePartDefinition[] matchingParts = this.GetPartsWithContract(definition.ContractName);
     if (matchingParts == null)
     {
         return Enumerable.Empty<Tuple<ComposablePartDefinition, ExportDefinition>>();
     }
     else
     {
         var exports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
         foreach (var part in matchingParts)
         {
             foreach (var export in part.ExportDefinitions)
             {
                 if (definition.IsConstraintSatisfiedBy(export))
                 {
                     exports.Add(new Tuple<ComposablePartDefinition, ExportDefinition>(part, export));
                 }
             }
         }
         return exports;
     }
 }
 private static IEnumerable<UnsuitableExportDefinitionIssue> CheckForTypeIdentityIssues(
     ContractBasedImportDefinition cbid, ExportDefinition ped)
 {
     if (cbid.RequiredTypeIdentity != null)
     {
         object actual;
         if (ped.Metadata.TryGetValue(
             CompositionConstants.ExportTypeIdentityMetadataName, out actual) &&
             actual != null)
         {
             var actualString = actual as string;
             if (actualString == null)
             {
                 yield return new UnsuitableExportDefinitionIssue(
                     UnsuitableExportDefinitionReason.TypeIdentity,
                     string.Format("ExportTypeIdentity is provided, but the metadata value is a '{0}'. The value should be a string.",
                         actual.GetType()));
             }
             else if (cbid.RequiredTypeIdentity != actualString)
             {
                 yield return new UnsuitableExportDefinitionIssue(
                     UnsuitableExportDefinitionReason.TypeIdentity,
                     string.Format("The export is a '{0}', but the import requires '{1}'. These types must match exactly (conversions are not supported.)",
                         actualString, cbid.RequiredTypeIdentity));
             }
         }
         else
         {
             yield return new UnsuitableExportDefinitionIssue(
                 UnsuitableExportDefinitionReason.TypeIdentity,
                 string.Format("Import requires '{0}', but export does not provide type information. This should be stored in ExportDefinition.Metadata[{1}].",
                     cbid.RequiredTypeIdentity, CompositionConstants.ExportTypeIdentityMetadataName));
         }
     }
 }
        private static IEnumerable<UnsuitableExportDefinitionIssue> CheckForRequiredMetadataIssues(
            ContractBasedImportDefinition cbid, ExportDefinition ped)
        {
            var missing = cbid
                .RequiredMetadata
                .Where(rm => !ped.Metadata.ContainsKey(rm.Key))
                .Select(rm => new UnsuitableExportDefinitionIssue(
                                    UnsuitableExportDefinitionReason.RequiredMetadata,
                                    string.Format("The import requires metadata '{0}' but this is not provided by the export.", rm)));

             var typeMismatch = cbid
                    .RequiredMetadata
                    .Join(
                        ped.Metadata,
                        rm => rm.Key,
                        m => m.Key,
                        (rm, m) => new { Key = rm.Key, RequiredType = rm.Value, Actual = m.Value })
                    .Where(info => info.Actual != null && !info.RequiredType.IsAssignableFrom(info.Actual.GetType()))
                    .Select(info => new UnsuitableExportDefinitionIssue(
                                    UnsuitableExportDefinitionReason.RequiredMetadata,
                                    string.Format("The import requires metadata '{0}' to be of type '{1}' but the provided value '{2}' is of type '{3}'",
                                        info.Key, info.RequiredType, info.Actual, info.Actual.GetType())));

             return missing.Concat(typeMismatch);
        }
Exemplo n.º 18
0
 public ImportingParameter(ContractBasedImportDefinition definition, ImportType importType)
     : base(definition, importType)
 {
 }
        public void Constructor2_ValueAsRequiredMetadataArgument_ShouldSetRequiredMetadataProperty()
        {
            var expectations = Expectations.GetRequiredMetadataWithEmpty();

            foreach (var e in expectations)
            {
                var definition = new ContractBasedImportDefinition("ContractName", (string)null, e, ImportCardinality.ExactlyOne, false, false, CreationPolicy.Any);

                EnumerableAssert.AreEqual(e, definition.RequiredMetadata);
            }
        }
		public void ApplicationCatalog(Type contractType, bool expectedIsDisposableNormal, bool expectedIsDisposableWrapped)
		{
			// ApplicationCatalog is a good comprehensive test because it uses the following hierarchy:
			// + AggregateCatalog
			//   + DirectoryCatalog
			//     + AssemblyCatalog
			//       + TypeCatalog

			using (var innerCatalog = new ApplicationCatalog())
			using (var wrapperCatalog = new DisposableWrapperCatalog(innerCatalog, false))
			{
				const ImportCardinality cardinality = ImportCardinality.ExactlyOne;
				var metadata = new Dictionary<string, object>();
				var typeIdentity = AttributedModelServices.GetTypeIdentity(contractType);
				var contractName = AttributedModelServices.GetContractName(contractType);
				var definition = new ContractBasedImportDefinition(contractName, typeIdentity, null, cardinality, false, true, CreationPolicy.Any, metadata);

				var partNormal = innerCatalog.GetExports(definition).Single().Item1.CreatePart();
				var partWrapped = wrapperCatalog.GetExports(definition).Single().Item1.CreatePart();

				var isDisposableNormal = partNormal is IDisposable;
				var isDisposableWrapped = partWrapped is IDisposable;

				Assert.AreEqual(expectedIsDisposableNormal, isDisposableNormal, "Checking Normal Part");
				Assert.AreEqual(expectedIsDisposableWrapped, isDisposableWrapped, "Checking Wrapped Part");
			}
		}
Exemplo n.º 21
0
 public static bool ShouldCreateClosedGenericPart(ContractBasedImportDefinition contractDef, Type importDefinitionType)
 {
     return contractDef.Cardinality != ImportCardinality.ZeroOrMore && importDefinitionType.IsGenericType;
 }
        public void RequiredMetadata_ArrayWithNullKeyAsRequiredMetadataArgument_ShouldThrowInvalidOperation()
        {
            var requiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>(null, typeof(object)) };

            var import = new ContractBasedImportDefinition("requiredMetadata", (string)null, requiredMetadata, ImportCardinality.ExactlyOne, false, false, CreationPolicy.Any);

            ExceptionAssert.Throws<InvalidOperationException>(() =>
            {
                var m = import.RequiredMetadata;
            });
        }
        public void Constraint_ShouldIncludeRequiredMetadataProperty()
        {
            var expectations = Expectations.GetRequiredMetadataWithEmpty();

            foreach (var e in expectations)
            {
                var definition = new ContractBasedImportDefinition("ContractName", (string)null, e, ImportCardinality.ExactlyOne, true, false, CreationPolicy.Any);

                ConstraintAssert.Contains(definition.Constraint, "ContractName", e);
            }
        }
        public void Constructor2_NullAsRequiredMetadataArgument_ShouldSetRequiredMetadataToEmptyEnumerable()
        {
            var definition = new ContractBasedImportDefinition("requiredMetadata", (string)null, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, false, false, CreationPolicy.Any);

            EnumerableAssert.IsEmpty(definition.RequiredMetadata);
        }
        public void Constructor2_ShouldSetRequiredCreationPolicyToAny()
        {
            var expectations = Expectations.GetEnumValues<CreationPolicy>();

            foreach (var e in expectations)
            {
                var definition = new ContractBasedImportDefinition("ContractName", (string)null, Enumerable.Empty<KeyValuePair<string, Type>>(), ImportCardinality.ExactlyOne, false, false, e);

                Assert.AreEqual(e, definition.RequiredCreationPolicy);
            }
        }
        public void Constructor2_ValueAsIsPrerequisiteArgument_ShouldSetIsPrerequisiteProperty()
        {
            var expectations = Expectations.GetBooleans();

            foreach (var e in expectations)
            {
                var definition = new ContractBasedImportDefinition("ContractName", (string)null, Enumerable.Empty<KeyValuePair<string, Type>>(), ImportCardinality.ExactlyOne, false, e, CreationPolicy.Any);

                Assert.AreEqual(e, definition.IsPrerequisite);
            }
        }
Exemplo n.º 27
0
 public static ContractBasedImportDefinition CreateExportFactoryImportDefinition(ContractBasedImportDefinition productImportDefinition)
 {
     return new ExportFactoryImportDefinition(productImportDefinition);
 }
        private IDictionary<string, object> TranslateImportMetadata(ContractBasedImportDefinition originalImport)
        {
            int[] importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName);
            if (importParametersOrder != null)
            {
                Dictionary<string, object> metadata = new Dictionary<string, object>(originalImport.Metadata, StringComparers.MetadataKeyNames);

                // Get the newly re-qualified name of the generic contract and the subset of applicable types from the specialization
                metadata[CompositionConstants.GenericContractMetadataName] = GenericServices.GetGenericName(originalImport.ContractName, importParametersOrder, this._specialization.Length);
                metadata[CompositionConstants.GenericParametersMetadataName] = GenericServices.Reorder(this._specialization, importParametersOrder);
                metadata.Remove(CompositionConstants.GenericImportParametersOrderMetadataName);

                return metadata.AsReadOnly();
            }
            else
            {
                return originalImport.Metadata;
            }
        }
Exemplo n.º 29
0
 public ExportFactoryImportDefinition(ContractBasedImportDefinition productImportDefinition)
     : base(CompositionConstants.PartCreatorContractName, CompositionConstants.PartCreatorTypeIdentity, productImportDefinition.RequiredMetadata,
         productImportDefinition.Cardinality, productImportDefinition.IsRecomposable, false, CreationPolicy.Any)
 {
     _productImportDefinition = productImportDefinition;
 }
        public void Constraint_ShouldIncludeContractNameProperty()
        {
            var expectations = Expectations.GetContractNames();

            foreach (var e in expectations)
            {
                var definition = new ContractBasedImportDefinition(e, (string)null, (IEnumerable<KeyValuePair<string, Type>>)null, ImportCardinality.ExactlyOne, true, false, CreationPolicy.Any);

                ConstraintAssert.Contains(definition.Constraint, e);
            }
        }
        public void Constructor2_ValueAsCardinalityArgument_ShouldSetCardinalityProperty()
        {
            var expectations = Expectations.GetEnumValues<ImportCardinality>();

            foreach (var e in expectations)
            {
                var definition = new ContractBasedImportDefinition("ContractName", (string)null, Enumerable.Empty<KeyValuePair<string, Type>>(), e, false, false, CreationPolicy.Any);

                Assert.AreEqual(e, definition.Cardinality);
            }
        }