/// <summary>
        /// Registers the specified object with its related lifetime manager, and the
        /// construction parameters used by the lifetime manager.
        /// </summary>
        /// <param name="serviceType">Type of service to register</param>
        /// <param name="serviceObjectType">Type of object implementing the service</param>
        /// <param name="parameters">Object construction parameters</param>
        /// <param name="properties">Object properties to inject</param>
        /// <param name="ltManager">Lifetime manager object</param>
        /// <param name="customContext"></param>
        public void Register(Type serviceType, Type serviceObjectType,
                             InjectedParameterSettingsCollection parameters = null,
                             PropertySettingsCollection properties          = null, ILifetimeManager ltManager = null,
                             object customContext = null)
        {
            if (serviceType == null)
            {
                throw new ArgumentNullException("serviceType");
            }
            if (serviceObjectType == null)
            {
                throw new ArgumentNullException("serviceObjectType");
            }
            if (_services.ContainsKey(serviceType))
            {
                throw new ServiceAlreadyRegisteredException(serviceType);
            }

            // --- Register the new mapping
            _services[serviceType] = new ServiceMapping(
                serviceType,
                serviceObjectType,
                ltManager ?? new PerCallLifetimeManager(),
                parameters,
                properties,
                customContext);

            // --- Reset lifetime managers
            foreach (var mapping in _services.Values)
            {
                mapping.LifetimeManager.ResetState();
                mapping.Resolved = false;
            }
        }
        /// <summary>
        /// Finds all constructors matching with the specified mapping
        /// </summary>
        private static ConstructorInfo[] FindMatchingConstructors(ServiceMapping mapping)
        {
            // --- Find matching constructors
            var ctorParamIndex = 0;
            var ctors          = mapping.ServiceObjectType.GetConstructors();

            foreach (var param in mapping.ConstructionParameters)
            {
                // --- This parameter should be matched directly
                ctors = (from ctor in ctors
                         let pars = ctor.GetParameters()
                                    where pars.Length > ctorParamIndex &&
                                    pars[ctorParamIndex].ParameterType == param.Type
                                    select ctor).ToArray();
                if (ctors.Length == 0)
                {
                    break;
                }
                ctorParamIndex++;
            }

            // --- If there are multiple candidates, try to obtains the one with exact number of arguments
            if (ctors.Length <= 1)
            {
                return(ctors);
            }
            var exactOne = ctors.Where(c => c.GetParameters().Length
                                       == mapping.ConstructionParameters.Count).ToArray();

            return(exactOne.Length == 1 ? exactOne : ctors);
        }
Beispiel #3
0
        public static async Task <ISampledService> GetServiceAsync(this IAsyncServiceProvider self, FileSample sample)
        {
            if (self is null)
            {
                throw new ArgumentNullException(nameof(self));
            }
            if (sample is null)
            {
                throw new ArgumentNullException(nameof(sample));
            }

            if (!ServiceMapping.TryGetValue(sample.GetType(), out Type serviceType))
            {
                return(null);
            }

            PlaySpaceManager playSpace = await self.GetServiceAsync <PlaySpaceManager> ().ConfigureAwait(false);

            await playSpace.Loading.ConfigureAwait(false);

            IEnumerable <IEnvironmentService> services = await self.GetServicesAsync <IEnvironmentService> ().ConfigureAwait(false);

            services = services.Where(s => serviceType.IsAssignableFrom(s.GetType()));

            PlaySpaceElement space = playSpace.SelectedElement;

            if (space != null)
            {
                services = services.Where(s => space.Services.Contains(s.GetType().GetSimpleTypeName()));
            }

            return((ISampledService)services.FirstOrDefault());
        }
 public Option <IPaged <TDto> > GetPaged(
     Option <int> pageNo,
     Option <int> pageSize,
     Option <string>[] sorts,
     Option <string> keyword)
 {
     return(ServiceMapping.GetPaged <T, TDto, TReadPagedInterceptor>(pageNo, pageSize, sorts, keyword));
 }
 public Task <Option <IPaged <TDto> > > GetPagedAsync(
     Option <int> pageNo,
     Option <int> pageSize,
     Option <string>[] sorts,
     Option <string> keyword,
     Option <CancellationToken> ctok)
 {
     return(ServiceMapping.GetPagedAsync <T, TDto, TReadPagedInterceptor>(pageNo, pageSize, sorts, keyword, ctok));
 }
Beispiel #6
0
            } // constructor

            public void Add(ServiceMapping mapping)
            {
                DomainFile domainFile;

                if (!files.TryGetValue(mapping.Logo, out domainFile))
                {
                    domainFile = new DomainFile(mapping.Logo);
                    files.Add(mapping.Logo, domainFile);
                } // if
                domainFile.Add(mapping);
            }     // Add
Beispiel #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // Configure AutoMapper
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // Configure DI
            RepositoryMapping.InitMap(services);
            ServiceMapping.InitMap(services);



            // Configure identity server
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                // Notice the schema name is case sensitive [ cookies != Cookies ]
                options.DefaultScheme          = "cookies";
                options.DefaultChallengeScheme = "oidc";
            })

            .AddCookie("cookies", options => options.ForwardDefaultSelector = ctx => ctx.Request.Path.StartsWithSegments("/api") ? "jwt" : "cookies")
            .AddJwtBearer("jwt", options =>
            {
                options.Authority            = "https://localhost:44359";
                options.Audience             = "api1";
                options.RequireHttpsMetadata = false;
            })
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme         = "cookies";
                options.Authority            = "https://localhost:44359";
                options.RequireHttpsMetadata = true;
                options.ClientId             = "mvc";
                options.SaveTokens           = true;

                options.ClientSecret = "secret";
                options.ResponseType = "code id_token";
                options.GetClaimsFromUserInfoEndpoint = true;
                options.Scope.Add("api1");
                options.Scope.Add("offline_access");

                options.ForwardDefaultSelector = ctx => ctx.Request.Path.StartsWithSegments("/api") ? "jwt" : "oidc";
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        /// <summary>
        /// Obtains the signature of the constructor specified by the mapping
        /// </summary>
        private static string GetConstructorSignature(ServiceMapping mapping)
        {
            // --- Create signature
            var needComma = false;
            var signature = new StringBuilder("(");

            foreach (var type in mapping.ConstructionParameters.Select(p => p.Type.FullName))
            {
                if (needComma)
                {
                    signature.Append(", ");
                }
                needComma = true;
                signature.Append(type);
            }
            signature.Append(")");
            return(signature.ToString());
        }
        /// <summary>
        /// Prepares constructor parameters.
        /// </summary>
        /// <param name="mapping">Service mapping information</param>
        /// <param name="visitedTypes">Types visited during resolution</param>
        /// <param name="ctor">Constructor to preapre</param>
        /// <returns>Array of constructor parameters</returns>
        private object[] PrepareConstructorParameters(ServiceMapping mapping, List <Type> visitedTypes, ConstructorInfo ctor)
        {
            var parTypes = ctor.GetParameters().Select(p => p.ParameterType).ToArray();
            var parCount = parTypes.Length;
            var ctorPars = new object[parCount];

            // --- Let's match the specified parameter values
            for (var i = 0; i < parCount; i++)
            {
                InjectedParameterSettings param;
                if (i < mapping.ConstructionParameters.Count &&
                    !(param = mapping.ConstructionParameters[i]).Resolve)
                {
                    // --- Use the specified value
                    if (param.Type == param.Value.GetType())
                    {
                        ctorPars[i] = param.Value;
                    }
                    else
                    {
                        var converter = TypeDescriptor.GetConverter(param.Type);
                        ctorPars[i] = converter.ConvertFromString(param.Value.ToString());
                    }
                }
                else
                {
                    // --- Resolve the instance from the container
                    var lastVisitedTypes = new List <Type>(visitedTypes);
                    var paramObject      = ((IServiceContainerEx)(this))
                                           .GetService(parTypes[i], lastVisitedTypes);
                    if (paramObject == null)
                    {
                        throw new NoMatchingConstructorException(mapping.ServiceObjectType,
                                                                 GetConstructorSignature(mapping), i);
                    }
                    ctorPars[i] = paramObject;
                }
            }
            return(ctorPars);
        }
        /// <summary>
        /// Resolves the lifetime manager of the specified mapping.
        /// </summary>
        /// <param name="mapping">Type mapping information</param>
        /// <param name="visitedTypes">Types visited during resolution</param>
        private void ResolveLifetimeManager(ServiceMapping mapping, List <Type> visitedTypes)
        {
            // --- Do not resolve again
            if (mapping.Resolved)
            {
                return;
            }

            // --- Obtain the appropriate constructor parameters
            var ctorPars = new object[0];

            if (mapping.ConstructionParameters != null)
            {
                var ctors = FindMatchingConstructors(mapping);
                if (ctors.Length != 1)
                {
                    // --- Check for ambiguity
                    var signature = GetConstructorSignature(mapping);
                    if (ctors.Length == 0)
                    {
                        throw new NoMatchingConstructorException(mapping.ServiceObjectType, signature);
                    }
                    throw new AmbigousConstructorException(mapping.ServiceObjectType, signature);
                }

                // --- At this point we have the only matching constructor, let's inject its parameters
                var ctor = ctors[0];
                ctorPars = PrepareConstructorParameters(mapping, visitedTypes, ctor);
            }

            // --- Prepare the lifetime manager
            var ltManager = mapping.LifetimeManager;

            ltManager.ServiceType            = mapping.ServiceType;
            ltManager.ServiceObjectType      = mapping.ServiceObjectType;
            ltManager.ConstructionParameters = ctorPars;
            ltManager.Properties             = mapping.Properties;
            ltManager.CustomContext          = mapping.CustomContext;
            mapping.Resolved = true;
        }
Beispiel #11
0
            } // constructor

            public void Add(ServiceMapping mapping)
            {
                services.Add(mapping);
            } // Add
Beispiel #12
0
 public Task <Option <TDto> > GetByPredicateAsync(Option <TDto> criteria, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.GetByPredicateAsync(criteria, ctok));
 }
Beispiel #13
0
 public Task <Option <bool> > Handle(Option <DeleteRequest <T, TDto> > request, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.DeleteEntityAsync(request.ReduceOrDefault().Criteria, ctok));
 }
Beispiel #14
0
 public Task <Option <TDto> > Handle(Option <ReadOneRequest <T, TDto> > request, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.GetByPredicateAsync(request.ReduceOrDefault().Criteria, ctok));
 }
Beispiel #15
0
 public Task <Option <List <KeyValue> > > Handle(Option <ReadLookupRequest <T, TDto> > request, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.GetLookupsAsync(request.ReduceOrDefault().UseValueAsId, ctok));
 }
 public Option <bool> DeleteEntity(Option <TDto> criteria)
 {
     return(ServiceMapping.DeleteEntity(criteria));
 }
 public Task <Option <bool> > DeleteEntityAsync(Option <TDto> criteria, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.DeleteEntityAsync(criteria, ctok));
 }
Beispiel #18
0
 public Task <Option <List <KeyValue> > > GetLookupsAsync(Option <bool> useValueAsId, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.GetLookupsAsync(useValueAsId, ctok));
 }
Beispiel #19
0
 public Option <List <KeyValue> > GetLookups(Option <bool> useValueAsId)
 {
     return(ServiceMapping.GetLookups(useValueAsId));
 }
Beispiel #20
0
        public Task RunAsync(BuildContext context)
        {
            var config = context.GetSharedObject(Constants.Config) as ConfigModel;

            if (config == null)
            {
                throw new ApplicationException(string.Format("Key: {0} doesn't exist in build context", Constants.Config));
            }
            var mappingConfig = config.ServiceMappingConfig;

            if (mappingConfig == null)
            {
                return(Task.FromResult(0));
            }
            string outputPath   = mappingConfig.OutputPath;
            var    articlesDict = context.GetSharedObject(Constants.ArticleItemYamlDict) as ConcurrentDictionary <string, ArticleItemYaml>;

            var newservices = (from article in articlesDict.Values
                               where article.Type == MemberType.Namespace
                               let serviceCategory = Find(mappingConfig.Mappings, FormatPath(article.Source.Path))
                                                     where serviceCategory != null
                                                     group article.Uid by serviceCategory into g
                                                     select g
                               ).ToDictionary(g => g.Key, g => g.ToList());

            ServiceMappingItem other = new ServiceMappingItem
            {
                name            = "Other",
                landingPageType = LandingPageTypeService,
                uid             = "azure.java.sdk.landingpage.services.other",
                children        = new List <string> {
                    "*"
                },
            };
            Dictionary <string, string> hrefMapping = new Dictionary <string, string>();

            if (File.Exists(outputPath))
            {
                using (var reader = new StreamReader(outputPath))
                {
                    var oldMapping = new YamlDeserializer(ignoreUnmatched: true).Deserialize <ServiceMapping>(reader);
                    foreach (var m in oldMapping[0].items)
                    {
                        if (m.name == "Other")
                        {
                            other = m;
                            continue;
                        }
                        hrefMapping[m.name] = m.href;
                        foreach (var c in m.items ?? Enumerable.Empty <ServiceMappingItem>())
                        {
                            var sc = new ServiceCategory {
                                Service = m.name, Category = c.name
                            };
                            Merge(newservices, sc, c.children?.ToList() ?? new List <string>());
                            hrefMapping[GetKey(m.name, c.name)] = c.href;
                        }
                    }
                }
            }
            var services = (from item in newservices
                            group item by item.Key.Service into g
                            select new
            {
                Service = g.Key,
                Items = (from v in g
                         group v.Value by v.Key.Category into g0
                         select new
                {
                    Category = g0.Key,
                    Uids = g0.SelectMany(i => i).OrderBy(i => i).Distinct().ToList()
                }).ToList(),
            }).ToDictionary(p => p.Service, p => p.Items);

            var mapping = new ServiceMapping()
            {
                new ServiceMappingItem()
                {
                    uid             = "azure.java.sdk.landingpage.reference",
                    name            = "Reference",
                    landingPageType = "Root",
                    items           = new ServiceMapping((from pair in services
                                                          let service = pair.Key
                                                                        let hrefAndType = GetHrefAndType(hrefMapping, service)
                                                                                          select new ServiceMappingItem()
                    {
                        name = service,
                        href = hrefAndType.Item1,
                        landingPageType = hrefAndType.Item2,
                        uid = "azure.java.sdk.landingpage.services." + FormatUid(service),
                        items = new ServiceMapping(from item in pair.Value
                                                   let category = item.Category
                                                                  let chrefAndType = GetHrefAndType(hrefMapping, GetKey(service, category))
                                                                                     select new ServiceMappingItem()
                        {
                            name = item.Category,
                            href = chrefAndType.Item1,
                            landingPageType = chrefAndType.Item2,
                            uid = "azure.java.sdk.landingpage.services." + FormatUid(service) + "." + category,
                            children = item.Uids.ToList()
                        })
                    }).OrderBy(s => s.name))
                }
            };

            mapping[0].items.Add(other);

            using (var writer = new StreamWriter(outputPath))
            {
                new YamlSerializer().Serialize(writer, mapping);
            }
            return(Task.FromResult(0));
        }
Beispiel #21
0
 protected BaseEntityService(Option <BaseUnitOfWork> uow, Option <TInterceptor> interceptor)
 {
     ServiceMapping = new ServiceMapping <T, TInterceptor>(uow, interceptor);
 }
Beispiel #22
0
 public Option <TDto> GetByPredicate(Option <TDto> criteria)
 {
     return(ServiceMapping.GetByPredicate(criteria));
 }
Beispiel #23
0
        public Task <Option <IPaged <TDto> > > Handle(Option <ReadPagedRequest <T, TDto> > request, Option <CancellationToken> ctok)
        {
            var x = request.ReduceOrDefault();

            return(ServiceMapping.GetPagedAsync <T, TDto, TReadPagedInterceptor>(x.PageNo, x.PageSize, x.Sorts, x.Keyword, ctok));
        }
 public Task <Option <Dictionary <string, object> > > UpdateEntityAsync(Option <TDto> dto, Option <CancellationToken> ctok)
 {
     return(ServiceMapping.UpdateEntityAsync(dto, ctok));
 }
 public Option <Dictionary <string, object> > UpdateEntity(Option <TDto> dto)
 {
     return(ServiceMapping.UpdateEntity(dto));
 }
Beispiel #26
0
 public Task <Option <Dictionary <string, object> > > Handle(
     Option <CreateRequest <T, TDto> > request,
     Option <CancellationToken> ctok)
 {
     return(ServiceMapping.CreateEntityAsync(request.ReduceOrDefault().Dto, ctok));
 }
Beispiel #27
0
 protected BaseRequestHandler(Option <BaseUnitOfWork> uow, Option <TInterceptor> interceptor)
 {
     ServiceMapping = new ServiceMapping <T, TInterceptor>(uow, interceptor);
 }