Beispiel #1
0
        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="key">        The key.</param>
        /// <returns>Returns an instance of <see cref="System.Object"/>.</returns>
        /// <exception cref="System.Exception">This exception will be thrown when XXX.</exception>
        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = "";

            try
            {
                contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
                var exports = _container.GetExportedValues <object>(contract).ToArray();

                if (exports.Any())
                {
                    return(exports.First());
                }
            }
            catch (Exception error)
            {
                int debug = 0;
            }

            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }
        public void GetExportContractName_should_return_contract_name_of_field_type_when_called_with_field_and_contract_name_and_type_are_null()
        {
            var member =
                ReflectionServices.GetField <FakePart>(x => x.Count);

            var convention =
                new ExportConvention
            {
                ContractName = null,
                ContractType = null,
                Members      = x => new[] { member }
            };

            var results =
                this.Service.GetExportContractName(convention, member);

            var expectedContractName =
                AttributedModelServices.GetContractName(member.FieldType);

            results.ShouldEqual(expectedContractName);
        }
Beispiel #3
0
        private void LoadReader(string pluginDir)
        {
            var categ = new DirectoryCatalog(pluginDir);
            var cname = AttributedModelServices.GetContractName(typeof(IEMailReader));
            Expression <Func <ExportDefinition, bool> > exp = a => a.ContractName == cname;
            var id = new ImportDefinition(exp, cname, ImportCardinality.ExactlyOne, true, true);
            var l  = categ.GetExports(id).ToList();

            if (l.Count == 1)
            {
                var cc = new CompositionContainer(categ);
                cc.ComposeParts(this);
                creader.Content    = Reader;
                Reader.QueryThread = OnQueryThread;
            }
            else if (l.Count == 0)
            {
                creader.Visibility = Visibility.Collapsed;
                MessageBox.Show("Failed to find any plugin!");
            }
        }
Beispiel #4
0
        static IEnumerable <ExportDefinition> GetExportDefinitions(Type implementationType, Type contractType, string key = null)
        {
            var lazyMember  = new LazyMemberInfo(implementationType);
            var contracName = key ?? AttributedModelServices.GetContractName(contractType);
            var metadata    = new Lazy <IDictionary <string, object> >(() =>
            {
                var md = new Dictionary <string, object>
                {
                    {
                        CompositionConstants.ExportTypeIdentityMetadataName,
                        AttributedModelServices.GetTypeIdentity(contractType)
                    }
                };
                return(md);
            });

            return(new[] {
                ReflectionModelServices.CreateExportDefinition(lazyMember, contracName, metadata, null),
                ReflectionModelServices.CreateExportDefinition(lazyMember, AttributedModelServices.GetContractName(contractType), metadata, null)
            });
        }
Beispiel #5
0
        public object TryGetService(Type serviceType)
        {
            var contract = AttributedModelServices.GetContractName(serviceType);
            var instance = AddToDisposables(TempContainer.GetExportedValueOrDefault <object>(contract));

            if (instance != null)
            {
                return(instance);
            }

            var sp = initialized ? syncServiceProvider : asyncServiceProvider;

            try
            {
                instance = sp.GetService(serviceType);
                if (instance != null)
                {
                    return(instance);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex, "Error loading {ServiceType}", serviceType);
            }

            instance = AddToDisposables(ExportProvider.GetExportedValues <object>(contract).FirstOrDefault(x => contract.StartsWith("github.", StringComparison.OrdinalIgnoreCase) ? x.GetType().Assembly.GetName().Version == currentVersion : true));

            if (instance != null)
            {
                return(instance);
            }

            instance = GitServiceProvider?.GetService(serviceType);
            if (instance != null)
            {
                return(instance);
            }

            return(null);
        }
        protected override object GetInstance(Type service, string key)
        {
            this.logger.Info("GetInstance {0}, {1}", service, key);
            string contract = String.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;

            IEnumerable <object> exports;

            try {
                exports = container.GetExportedValues <object>(contract);
            }
            catch (System.Exception ex) {
                this.logger.Error(ex);
                throw;
            }

            if (exports.Any())
            {
                return(exports.First());
            }

            throw new ArgumentException(String.Format("Could not locate any instances of contract {0}.", contract));
        }
Beispiel #7
0
 /// <summary>
 /// Gets the name used to persist the event in the event store.
 /// </summary>
 /// <remarks>By default, this is the event class's type name, with no namespace. This name can be specified by adding the EventNameAttribute to the class.</remarks>
 /// <returns>A string representing the class's name.</returns>
 public static string EventName(this Type eventType)
 {
     // TODO: (EventExtensions) differentiate these two methods in terms of use cases. it's potentially misleading since they can return different values
     return(eventNames2.GetOrAdd(eventType,
                                 t => t.GetCustomAttributes(false)
                                 .OfType <EventNameAttribute>()
                                 .FirstOrDefault()
                                 .IfNotNull()
                                 .Then(att => att.EventName)
                                 .Else(() =>
     {
         if (t.IsGenericType)
         {
             var contractName = AttributedModelServices.GetContractName(t);
             // e.g. Microsoft.Its.Domain.Event(Microsoft.Its.SomeAggregate) --> Event(SomeAggregate)
             contractName = new Regex(@"([0-9\w\+]+\.)|([0-9\w\+]+\+)([\(\)]*)").Replace(contractName,
                                                                                         "$3");
             return contractName;
         }
         return t.Name;
     })));
 }
Beispiel #8
0
        public EMailAttachments()
        {
            InitializeComponent();
            GBB.Header = Properties.Resources.AttachmentsWordQ;
            GBC.Header = Properties.Resources.PreviewWord;
            (LstAttach.View as GridView).Columns[0].Header = Properties.Resources.NameWord;
            var dir = Assembly.GetExecutingAssembly().CodeBase.Substring("file:///".Length).Replace('/', '\\');

            dir = dir.Substring(0, dir.LastIndexOf('\\'));
            var categ = new DirectoryCatalog(dir);
            var cname = AttributedModelServices.GetContractName(typeof(IImageViewer));
            Expression <Func <ExportDefinition, bool> > exp = a => a.ContractName == cname;
            var id = new ImportDefinition(exp, cname, ImportCardinality.ExactlyOne, true, true);
            var l  = categ.GetExports(id).ToList();

            if (l.Count == 1)
            {
                var cc = new CompositionContainer(categ);
                cc.ComposeParts(this);
                cviewer.Content = ImageViewer;
            }
        }
Beispiel #9
0
        /// <summary>
        /// Removes a service from the catalog
        /// </summary>
        /// <param name="t">The type we want to remove</param>
        /// <param name="owner">The owner, which either has to match what was passed to AddService,
        /// or if it's null, the service will be removed without checking for ownership</param>
        public void RemoveService(Type t, object owner)
        {
            Guard.ArgumentNotNull(t, nameof(t));

            string contract = AttributedModelServices.GetContractName(t);

            Debug.Assert(!string.IsNullOrEmpty(contract), "Every type must have a contract name");

            OwnedComposablePart part;

            if (tempParts.TryGetValue(contract, out part))
            {
                if (owner != null && part.Owner != owner)
                {
                    return;
                }
                tempParts.Remove(contract);
                var batch = new CompositionBatch();
                batch.RemovePart(part.Part);
                TempContainer.Compose(batch);
            }
        }
Beispiel #10
0
        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()));
            }
        }
Beispiel #11
0
        public void RemoveService(Type t)
        {
            if (!Initialized)
            {
                log.Error("ExportProvider is not initialized, cannot remove service.");
                return;
            }

            string contract = AttributedModelServices.GetContractName(t);

            Debug.Assert(!string.IsNullOrEmpty(contract), "Every type must have a contract name");

            ComposablePart part;

            if (tempParts.TryGetValue(contract, out part))
            {
                tempParts.Remove(contract);
                var batch = new CompositionBatch();
                batch.RemovePart(part);
                tempContainer.Compose(batch);
            }
        }
        public IronPythonComposablePart(IronPythonTypeWrapper typeWrapper, IEnumerable <Type> exports, IEnumerable <KeyValuePair <string, IronPythonImportDefinition> > imports, IDictionary <object, object> exportMetadatas)
        {
            _typeWrapper = typeWrapper;
            _instance    = typeWrapper.Activator();
            _exports     = new List <ExportDefinition>(exports.Count());
            _imports     = new Dictionary <string, ImportDefinition>(imports.Count());
            foreach (var export in exports)
            {
                var metadata = new Dictionary <string, object>()
                {
                    { "ExportTypeIdentity", AttributedModelServices.GetTypeIdentity(export) }
                };

                if (exportMetadatas != null)
                {
                    foreach (var data in exportMetadatas)
                    {
                        metadata.Add(data.Key.ToString(), data.Value);
                    }
                }

                var contractName = AttributedModelServices.GetContractName(export);
                _exports.Add(new ExportDefinition(contractName, metadata));
            }
            foreach (var import in imports)
            {
                var contractName = AttributedModelServices.GetContractName(import.Value.Type);
                var metadata     = new Dictionary <string, Type>();

                _imports[import.Key] = new IronPythonContractBasedImportDefinition(
                    import.Key,
                    contractName,
                    AttributedModelServices.GetTypeIdentity(import.Value.Type),
                    metadata.ToList(),
                    import.Value.Cardinality, import.Value.IsRecomposable, import.Value.IsPrerequisite,
                    CreationPolicy.Any);
            }
        }
        private IEnumerable <ImportDefinition> GetImportDefinitions(Type implementationType)
        {
            var imports            = new List <ImportDefinition>();
            var defaultConstructor = implementationType.GetConstructors().FirstOrDefault();

            if (defaultConstructor != null)
            {
                foreach (var param in defaultConstructor.GetParameters())
                {
                    imports.Add(
                        ReflectionModelServices.CreateImportDefinition(
                            new Lazy <ParameterInfo>(() => param),
                            AttributedModelServices.GetContractName(param.ParameterType),
                            AttributedModelServices.GetTypeIdentity(param.ParameterType),
                            Enumerable.Empty <KeyValuePair <string, Type> >(),
                            ImportCardinality.ExactlyOne,
                            CreationPolicy.Any,
                            null));
                }
            }

            return(imports);
        }
        public static object GetExportedValueByType(this CompositionContainer container, Type type)
        {
            foreach (var partDef in container.Catalog.Parts)
            {
                foreach (var exportDef in partDef.ExportDefinitions)
                {
                    if (exportDef.ContractName != type.FullName)
                    {
                        continue;
                    }
                    var contract   = AttributedModelServices.GetContractName(type);
                    var definition = new ContractBasedImportDefinition(contract, contract, null, ImportCardinality.ExactlyOne,
                                                                       false, false, CreationPolicy.Any);
                    var firstOrDefault = container.GetExports(definition).FirstOrDefault();
                    if (firstOrDefault != null)
                    {
                        return(firstOrDefault.Value);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// IOC容器获取实例的方法
        /// </summary>
        /// <param name="service"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        protected override object GetInstance(Type service, string key)
        {
            //try
            //{
            //    var obj = service?.Assembly.CreateInstance(service.FullName);
            //    return obj;
            //}
            //catch (Exception ex)
            //{
            //    return null;
            //}

            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(service) : key;
            var    exports  = m_container.GetExportedValues <object>(contract);

            var exportList = exports.ToList();//避免直接用exports时 调用2次IEnumerable操作

            if (exportList.Any())
            {
                return(exportList.First());
            }
            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }
 public static object GetService(Type serviceType)
 {
     if (typeof(IEnumerable).IsAssignableFrom(serviceType) && serviceType.GenericTypeArguments.Length == 1)
     {
         var itemType        = serviceType.GenericTypeArguments.First();
         var contractName    = AttributedModelServices.GetContractName(itemType);
         var items           = container.GetExportedValues <object>(contractName);
         var listGenericType = typeof(List <>);
         var list            = listGenericType.MakeGenericType(itemType);
         var ci       = list.GetConstructor(new Type[] { typeof(int) });
         var instance = ci.Invoke(new object[] { items.Count(), }) as IList;
         foreach (var item in items)
         {
             instance.Add(item);
         }
         return(instance);
     }
     else
     {
         var contractName = AttributedModelServices.GetContractName(serviceType);
         return(container.GetExportedValue <object>(contractName));
     }
 }
Beispiel #17
0
        public void AddService(Type t, object owner, object instance)
        {
            if (!Initialized)
            {
                log.Error("ExportProvider is not initialized, cannot add service.");
                return;
            }

            string contract = AttributedModelServices.GetContractName(t);

            Debug.Assert(!string.IsNullOrEmpty(contract), "Every type must have a contract name");

            // we want to remove stale instances of a service, if they exist, regardless of who put them there
            RemoveService(t, null);

            var batch = new CompositionBatch();
            var part  = batch.AddExportedValue(contract, instance);

            Debug.Assert(part != null, "Adding an exported value must return a non-null part");
            tempParts.Add(contract, new OwnedComposablePart {
                Owner = owner, Part = part
            });
            tempContainer.Compose(batch);
        }
Beispiel #18
0
        private IEnumerable <Export> GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality)
        {
            // Only 'type' cannot be null - the other parameters have sensible defaults.
            Requires.NotNull(type, nameof(type));

            if (string.IsNullOrEmpty(contractName))
            {
                contractName = AttributedModelServices.GetContractName(type);
            }

            if (metadataViewType == null)
            {
                metadataViewType = ExportServices.DefaultMetadataViewType;
            }

            if (!MetadataViewProvider.IsViewTypeValid(metadataViewType))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.InvalidMetadataView, metadataViewType.Name));
            }

            ImportDefinition importDefinition = BuildImportDefinition(type, metadataViewType, contractName, cardinality);

            return(GetExports(importDefinition, null));
        }
        public object TryGetService(Type serviceType)
        {
            var contract = AttributedModelServices.GetContractName(serviceType);
            var instance = AddToDisposables(TempContainer.GetExportedValueOrDefault <object>(contract));

            if (instance != null)
            {
                return(instance);
            }

            var sp = _initialized ? _syncServiceProvider : _asyncServiceProvider;

            try
            {
                instance = sp.GetService(serviceType);
                if (instance != null)
                {
                    return(instance);
                }
            }
            catch
            {
            }

            instance = AddToDisposables(ExportProvider.GetExportedValues <object>(contract).FirstOrDefault(x =>
                                                                                                           !contract.StartsWith("SharperCryptoApiAnalysis.", StringComparison.OrdinalIgnoreCase) ||
                                                                                                           x.GetType().Assembly.GetName().Version == _currentVersion));

            if (instance != null)
            {
                return(instance);
            }

            instance = ServiceProvider?.GetService(serviceType);
            return(instance);
        }
        /// <summary>
        ///
        /// </summary>
        /// <see cref="ServiceLocatorBase.OnGetInstance(Type, object)" />
        protected override object OnGetInstance(Type serviceType, object key)
        {
            var strKey = key.AsString(true);

            var container = this._PROVIDER as CompositionContainer;

            if (container != null)
            {
                // handle as extended composition container

                return(InvokeGetExportedValueMethod(c => c.GetExportedValue <object>(),
                                                    container,
                                                    serviceType,
                                                    strKey));
            }

            // old skool ...

            if (strKey == null)
            {
                strKey = AttributedModelServices.GetContractName(serviceType);
            }

            var lazyInstance = this._PROVIDER
                               .GetExports <object>(strKey)
                               .FirstOrDefault();

            if (lazyInstance != null)
            {
                // found
                return(lazyInstance.Value);
            }

            // not found
            return(null);
        }
Beispiel #21
0
        public void when_retrieving_exports_then_reports_duplicate_services(Type serviceType)
        {
            var componentModel = GlobalServices.GetService <SComponentModel, IComponentModel>();
            var contractName   = AttributedModelServices.GetContractName(serviceType);
            var components     = componentModel.DefaultExportProvider
                                 .GetExports <object, IDictionary <string, object> >(contractName)
                                 .ToArray();

            if (components.Length != 1)
            {
                var info = new CompositionInfo(componentModel.DefaultCatalog, componentModel.DefaultExportProvider);
                var log  = Path.GetTempFileName();
                using (var writer = new StreamWriter(log))
                {
                    CompositionInfoTextFormatter.Write(info, writer);
                    writer.Flush();
                }

                output.WriteLine(log);
                // Process.Start(new ProcessStartInfo("notepad", log) { UseShellExecute = true });

                Assert.False(true, $"Expected only one component of {serviceType.Name}. Composition log at {log}");
            }
        }
Beispiel #22
0
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        public NancyRegistrationBuilder()
            : base()
        {
            // export FuncFactory as an open generic instance; but more importantly, export its CreateExport function
            // as an appropriate Func<T> contract.
            ForType(typeof(FuncFactory <>))
            .AddMetadata(NancyMetadataKeys.RegistrationBuilder, this)
            .Export(i => i
                    .AsContractType(typeof(FuncFactory <>)))
            .ExportProperties(i =>
                              i == ExportFuncPropertyInfo, (i, j) => j
                              .AsContractType(typeof(Func <>))
                              .AsContractName("FuncFactory:" + AttributedModelServices.GetContractName(typeof(Func <>))));

            // export any exportable parts
            ForTypesMatching(i => IsExportableNancyPart(i))
            .AddMetadata(NancyMetadataKeys.RegistrationBuilder, this)
            .Export()
            .ExportInterfaces(i => IsNancyContract(i), (i, j) => j
                              .AsContractType(i))
            .SelectConstructor(i =>
                               SelectConstructor(i), (i, j) =>
                               BuildParameter(i, j));
        }
Beispiel #23
0
        public object GetService(Type serviceType)
        {
            string contractName = AttributedModelServices.GetContractName(serviceType);

            try
            {
                return(Container.GetExportedValueOrDefault <object>(contractName));
            }
            catch (Exception ex)
            {
                if (ex is System.Reflection.ReflectionTypeLoadException)
                {
                    var    typeLoadException = ex as ReflectionTypeLoadException;
                    var    loaderExceptions  = typeLoadException.LoaderExceptions;
                    string message           = string.Empty;
                    foreach (var item in loaderExceptions)
                    {
                        message += item.Message + ";";
                    }
                    throw new Exception(message);
                }
                throw;
            }
        }
        public void GetImportContractName_should_return_contract_name_for_property_type_when_called_with_property_and_contract_name_and_type_are_null()
        {
            var member =
                ReflectionServices.GetProperty <FakePart>(x => x.Name);

            var convention =
                new ImportConvention()
            {
                ContractName = null,
                ContractType = null,
                Members      = x => new[] { member }
            };

            var service =
                GetServiceWithoutDefaultConventions();

            var results =
                service.GetImportContractName(convention, member);

            var expectedContractName =
                AttributedModelServices.GetContractName(member.PropertyType);

            results.ShouldEqual(expectedContractName);
        }
 protected override IEnumerable <object> GetAllInstances(Type service)
 {
     return(m_Container.GetExportedValues <object>(AttributedModelServices.GetContractName(service)));
 }
        protected override object GetInstance(Type serviceType, string key)
        {
            string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;

            return(_container.GetExportedValue <object>(contract));
        }
        private static string CreateDisplayNameExpectationFromContractName(ReflectionParameterImportDefinition definition, Type type)
        {
            string contractName = AttributedModelServices.GetContractName(type);

            return(string.Format("{0} (Parameter=\"\", ContractName=\"{1}\")", definition.ImportingLazyParameter.Value.Member.GetDisplayName(), contractName));
        }
 private static ReflectionParameterImportDefinition CreateReflectionParameterImportDefinition(ParameterInfo parameter)
 {
     return(new ReflectionParameterImportDefinition(
                parameter.AsLazy(), AttributedModelServices.GetContractName(parameter.ParameterType), (string)null, null, ImportCardinality.ZeroOrMore, CreationPolicy.NonShared, null, null));
 }
Beispiel #29
0
        /// <summary>
        /// Extension method to searches the composition container for an export that has a matching type name. This function
        /// will first try to match on Type.AssemblyQualifiedName, then Type.FullName, and finally on Type.Name
        ///
        /// This method will not throw if multiple types are found matching the name, it will just return the first one it finds.
        /// </summary>
        /// <typeparam name="T">The type of the export</typeparam>
        /// <param name="typeName">The name of the type to find. This can be an assembly qualified name, a full name, or just the type's name</param>
        /// <returns>The export instance</returns>
        public T GetExportedValueByTypeName <T>(string typeName)
            where T : class
        {
            try
            {
                lock (_exportedValuesLockObject)
                {
                    T           instance;
                    IEnumerable values;
                    var         type = typeof(T);
                    if (_exportedValues.TryGetValue(type, out values))
                    {
                        // if we've alread loaded this part, then just reserve the same one
                        instance = values.OfType <T>().FirstOrDefault(x => x.GetType().MatchesTypeName(typeName));
                        if (instance != null)
                        {
                            return(instance);
                        }
                    }

                    // we want to get the requested part without instantiating each one of that type
                    var selectedPart = _compositionContainer.Catalog.Parts
                                       .Select(x => new { part = x, Type = ReflectionModelServices.GetPartType(x).Value })
                                       .Where(x => type.IsAssignableFrom(x.Type))
                                       .Where(x => x.Type.MatchesTypeName(typeName))
                                       .Select(x => x.part)
                                       .FirstOrDefault();

                    if (selectedPart == null)
                    {
                        throw new ArgumentException(
                                  "Unable to locate any exports matching the requested typeName: " + typeName, "typeName");
                    }

                    var exportDefinition =
                        selectedPart.ExportDefinitions.First(
                            x => x.ContractName == AttributedModelServices.GetContractName(type));
                    instance = (T)selectedPart.CreatePart().GetExportedValue(exportDefinition);

                    // cache the new value for next time
                    if (values == null)
                    {
                        values = new List <T> {
                            instance
                        };
                        _exportedValues[type] = values;
                    }
                    else
                    {
                        ((List <T>)values).Add(instance);
                    }

                    return(instance);
                }
            }
            catch (ReflectionTypeLoadException err)
            {
                foreach (var exception in err.LoaderExceptions)
                {
                    Log.Error(exception);
                    Log.Error(exception.ToString());
                }

                if (err.InnerException != null)
                {
                    Log.Error(err.InnerException);
                }

                throw;
            }
        }
Beispiel #30
0
 /// <summary>
 /// Locate all of the MEF exports registered as supplying contract type T.
 /// </summary>
 /// <typeparam name="T">The contract type.</typeparam>
 /// <param name="context">The context to resolve exports from.</param>
 /// <returns>A list of exports.</returns>
 public static IEnumerable <Export> ResolveExports <T>(this IComponentContext context)
 {
     return(context.ResolveExports <T>(AttributedModelServices.GetContractName(typeof(T))));
 }