Ejemplo n.º 1
0
        public void DictionaryServiceSetPropertyGuidTest()
        {
            var dictionaryService = Resolver.Resolve <IDictionaryService>();

            dictionaryService.SetEntry(_propertyGuid, 20);
            Assert.Equal(20, dictionaryService.GetEntry <int>(_propertyGuid));
        }
Ejemplo n.º 2
0
        public JObject Generate()
        {
            var data             = _httpContextProxy.GetRequestBody <GenerateAuthTokenRequest>();
            var userAccontHelper = _serviceResolver.Resolve <UserAccontHelper>();

            if (userAccontHelper.ValidateUser(data.UserName, data.Password))
            {
                var user = userAccontHelper.GetUser(data.UserName);
                if (GetAuthTokenCount(_dbService, user) < MAX_KEYS)
                {
                    var apikey     = GenerateApiKey();
                    var apikeydata = GenerateApiKeyData(user, apikey);

                    if (_dbService.WriteData(CommonConst.Collection.AUTH_TOKEN_COLLECTION, apikeydata))
                    {
                        apikeydata[CommonConst.CommonField.AUTH_TOKEN] = apikey;
                        return(_responseBuilder.Success(apikeydata));
                    }
                    else
                    {
                        _logger.Error("Error in writing data");
                        return(_responseBuilder.ServerError());
                    }
                }
                else
                {
                    return(_responseBuilder.CreateReponse(ApiKeyResponseCode._MAX_AUTH_TOKEN_REACHED));
                }
            }
            else
            {
                return(_responseBuilder.Unauthorized());
            }
        }
Ejemplo n.º 3
0
        public TResult Query <TRequest, TResult>(TRequest request)
        {
            HandleQuery <TRequest, TResult> handler = _resolver.Resolve <HandleQuery <TRequest, TResult> >();

            TResult result = handler.Query(request, this, ContextScopeManager.Current);

            return(result);
        }
Ejemplo n.º 4
0
        public MessageEntryTransform(IServiceResolver resolver)
        {
            _resolver = resolver;

            this.EntityType = typeof(MessageEntry);
            this.ModelType  = typeof(Axis.Pollux.Communication.Models.MessageEntry);

            this.CreateEntity = model => new MessageEntry();
            this.CreateModel  = entity => new Axis.Pollux.Communication.Models.MessageEntry();

            this.ModelToEntity = (m, e, command, context) =>
            {
                var model = (Axis.Pollux.Communication.Models.MessageEntry)m;
                model.Id = command == TransformCommand.Add ? Guid.NewGuid() : model.Id;
                var entity = model.TransformBase(
                    (MessageEntry)e,
                    command,
                    context,
                    _resolver);

                entity.Channel            = model.Channel;
                entity.DestinationAddress = model.DestinationAddress;

                var serializer = _resolver.Resolve <IDataSerializer>();
                entity.Payload = model.Payload == null
                    ? null
                    : serializer.SerializeData(model.Payload.GetType(), model.Payload).Resolve();

                entity.RenderedMessage = model.RenderedMessage;
                entity.RenderedTitle   = model.RenderedTitle;
                entity.SourceAddress   = model.SourceAddress;
                entity.Status          = model.Status;
                entity.TargetUserId    = model.TargetUserId;
            };

            this.EntityToModel = (e, m, command, context) =>
            {
                var entity = (MessageEntry)e;
                var model  = entity.TransformBase(
                    (Axis.Pollux.Communication.Models.MessageEntry)m,
                    command,
                    context,
                    _resolver);

                model.Channel            = entity.Channel;
                model.DestinationAddress = entity.DestinationAddress;
                model.RenderedMessage    = entity.RenderedMessage;
                model.RenderedTitle      = entity.RenderedTitle;
                model.SourceAddress      = entity.SourceAddress;
                model.Status             = entity.Status;
                model.TargetUserId       = entity.TargetUserId;

                var serializer = _resolver.Resolve <IDataSerializer>();
                model.Payload = string.IsNullOrWhiteSpace(entity.Payload)
                    ? null
                    : serializer.Deserialize <IMessagePayload>(entity.Payload).Resolve();
            };
        }
Ejemplo n.º 5
0
        public static IFileDownloadService ResolveFileDownloadService(RssFeedType type, IServiceResolver resolver)
        {
            switch (type)
            {
            case RssFeedType.Youtube:
                return(resolver.Resolve <YoutubeFileService>());

            default:
                return(resolver.Resolve <HttpFileDownloadService>());
            }
        }
Ejemplo n.º 6
0
        public static IFeedReader ResolveFeedReadeer(RssFeedType type, IServiceResolver resolver)
        {
            switch (type)
            {
            case RssFeedType.Youtube:
                return(resolver.Resolve <YoutubeFeedReader>());

            case RssFeedType.ITunes:
                return(resolver.Resolve <ITunesFeedReader>());

            default:
                throw new ArgumentException();
            }
        }
Ejemplo n.º 7
0
        private async Task <InvokeRoutineResult> RunRoutineAsync(
            ITransitionCarrier transitionCarrier,
            TransitionDescriptor transitionDescriptor,
            CancellationToken ct)
        {
            var invocationResult = new InvokeRoutineResult();

            using (_transitionScope.Enter(transitionDescriptor))
            {
                var transitionMonitor = _transitionScope.CurrentMonitor;

                var serviceId = await transitionCarrier.GetServiceIdAsync(ct);

                var methodId = await transitionCarrier.GetRoutineDescriptorAsync(ct);

                var serviceReference = _serviceResolver.Resolve(serviceId);
                var methodReference  = _methodResolver.Resolve(serviceReference.Definition, methodId);

                object serviceInstance = serviceReference.GetInstance();

                //var serviceStateContainer = _serviceStateValueContainerProvider.CreateContainer(serviceInstance);
                //var isStatefullService = serviceStateContainer.GetCount() > 0;
                //if (isStatefullService)
                //    await transitionCarrier.ReadServiceStateAsync(serviceStateContainer, ct);

                Type taskResultType =
                    methodReference.Definition.MethodInfo.ReturnType == typeof(void)
                    ? TaskAccessor.VoidTaskResultType
                    : TaskAccessor.GetTaskResultType(methodReference.Definition.MethodInfo.ReturnType);

                Task            completionTask;
                IValueContainer asmValueContainer = null;

                if (TryCreateAsyncStateMachine(methodReference.Definition.MethodInfo, methodId.IntentId, out var asmInstance, out var asmMetadata))
                {
                    var isContinuation = transitionDescriptor.Type == TransitionType.ContinueRoutine;
                    asmValueContainer = await LoadRoutineStateAsync(transitionCarrier, asmInstance, asmMetadata, isContinuation, ct);

                    asmMetadata.Owner.FieldInfo?.SetValue(asmInstance, serviceInstance);

                    transitionMonitor.OnRoutineStart(
                        serviceReference,
                        methodReference,
                        methodId,
                        serviceInstance,
                        asmInstance,
                        (transitionCarrier as TransitionCarrier)?.Caller);

                    try
                    {
                        asmInstance.MoveNext();
                        completionTask = GetCompletionTask(asmInstance, asmMetadata);
                    }
                    catch (Exception ex)
                    {
                        // The MoveNext() must not throw, but instead complete the task with an error.
                        // try-catch is added just in case for a non-compiler-generated state machine.
                        completionTask = TaskAccessor.FromException(taskResultType, ex);
                    }
                }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            //创建一个容器
            IServiceContainer services = new ServiceContainer();

            services.Configure(config =>
            {
                config.Interceptors.AddTyped <SampleInterceptor>();
            });

            services.AddType <ISampleService, SampleService>();
            services.AddType <ISampleRepository, SampleRepository>();

            //使用类型注册服务
            services.AddType <ILogger, Logger>();
            //使用实例注册服务,服务的生命周期限定为单例
            services.AddInstance <ITaskService>(new TaskService());
            //使用委托工厂注册服务
            services.AddDelegate <ITaskService, TaskService>(resolver => new TaskService());

            //创建服务解析器
            IServiceResolver serviceResolver = services.Build();

            //解析单个服务
            ISampleService sampleService = serviceResolver.Resolve <ISampleService>();

            //解析单个服务,并且验证是否为null,为null则抛出异常
            ISampleService sampleServiceRequired = serviceResolver.ResolveRequired <ISampleService>();

            //解析服务集合,如果未注册,则为空集合
            IEnumerable <ISampleService> sampleServices = serviceResolver.ResolveMany <ISampleService>();
        }
Ejemplo n.º 9
0
        public void Send <TCommand>(TCommand command) where TCommand : ICommand
        {
            var commandHandlerType = typeof(ICommandHandler <TCommand>);
            var commandHandler     = _resolver.Resolve(commandHandlerType) as ICommandHandler <TCommand>;

            commandHandler?.Handle(command);
        }
Ejemplo n.º 10
0
        private EventingHttpClient CreateEventingClient(ServiceId serviceId)
        {
            var serviceRef = _serviceResolver.Resolve(serviceId);

            var configuration = _communicationModelConfiguration.GetCommandsConfiguration(serviceRef.Definition, "communication");
            var settings      = new HttpCommunicatorSettings();

            configuration.Bind(settings);

            var serializer = string.IsNullOrEmpty(settings.Serializer)
                ? _defaultSerializerProvider.DefaultSerializer
                : _serializerProvider.GetSerializer(settings.Serializer);
            var compressPayload = settings.Compress ?? false;
            var urlTemplate     = HttpCommunicationMethod.GetUrlTemplate(settings);

            var schemeDelimiterIndex = urlTemplate.IndexOf("://");
            var firstSegmentIndex    = urlTemplate.IndexOf('/', schemeDelimiterIndex > 0 ? schemeDelimiterIndex + 3 : 0);
            var address = firstSegmentIndex > 0 ? urlTemplate.Substring(0, firstSegmentIndex) : urlTemplate;

            address = address.Replace("{serviceName}", serviceRef.Definition.Name);

            var urlBase = address + "/dev/events";

            return(new EventingHttpClient(serializer, urlBase));
        }
Ejemplo n.º 11
0
 public static T Resolve <T>(this IServiceResolver serviceResolver)
 {
     if (serviceResolver == null)
     {
         throw new ArgumentNullException(nameof(serviceResolver));
     }
     return((T)serviceResolver.Resolve(typeof(T)));
 }
Ejemplo n.º 12
0
        public object Resolve(Type type)
        {
            if (type == typeof(IPackageAuthenticationService))
            {
                return(new CustomPackageAuthenticationService());
            }

            return(_innerServiceResolver.Resolve(type));
        }
Ejemplo n.º 13
0
            public IEnumerable <object> GetServices(Type serviceType)
            {
                var service = _resolver.Resolve(serviceType);

                if (service != null)
                {
                    yield return(service);
                }
            }
Ejemplo n.º 14
0
        public static IServiceResolver CreateScope(this IServiceResolver serviceResolver)
        {
            if (serviceResolver == null)
            {
                throw new ArgumentNullException(nameof(serviceResolver));
            }
            var factory = serviceResolver.Resolve <IScopeResolverFactory>();

            return(factory.CreateScope());
        }
Ejemplo n.º 15
0
        public WithLoaderFrame(
            IAppLoaderService appLoaderService,
            IServiceResolver serviceResolver)
        {
            this.DefaultStyleKey = typeof(WithLoaderFrame);
            AppLoaderService     = appLoaderService;

            _serviceResolver   = serviceResolver;
            _navigationService = new Lazy <INavigationService>(() => _serviceResolver.Resolve <INavigationService>());
        }
Ejemplo n.º 16
0
 public async Task Invoke(HttpContext context)
 {
     try
     {
         var txnId = context.Request.Headers[CommonConst.CommonField.TRANSACTION_ID];
         if (string.IsNullOrEmpty(txnId))
         {
             txnId = CommonUtility.GenerateTxnId();
         }
         context.Response.Headers.Add("powered-by", "znxt.app");
         context.Response.Headers.Add(CommonConst.CommonField.TRANSACTION_ID, txnId);
         context.Response.Headers.Add(CommonConst.CommonField.CREATED_DATA_DATE_TIME, CommonUtility.GetTimestampMilliseconds(DateTime.Now).ToString());
         await _next(context);
     }
     catch (Exception ex)
     {
         _serviceResolver.Resolve <ILogger>().Error(ex.Message, ex);
         await context.Response.WriteAsync(_serviceResolver.Resolve <IResponseBuilder>().ServerError(ex.Message).ToString());
     }
 }
Ejemplo n.º 17
0
 public IList<IService> Resolve(IServiceResolver resolver, string protocol, TimeSpan timeout, int minServiceCountFound, int maxServiceCountFound)
 {
     resolver.ServiceFound += new ObjectEvent<IService>(resolver_ServiceFound);
     resolver.ServiceRemoved += new ObjectEvent<IService>(resolver_ServiceRemoved);
     resolver.Resolve(protocol);
     for (int i = minServiceCountFound; i <= maxServiceCountFound; i++)
         syncLock.WaitOne(timeout);
     resolver.ServiceFound -= resolver_ServiceFound;
     resolver.ServiceRemoved -= resolver_ServiceRemoved;
     return services;
 }
Ejemplo n.º 18
0
        public object Invoke(IServiceResolver resolver, object instance, ServiceDefinition service)
        {
            if (instance == null || !service.RequiredPropertyInjection())
            {
                return(instance);
            }
            var injectorFactory = resolver.Resolve <IPropertyInjectorFactory>();
            var injector        = injectorFactory.Create(instance.GetType());

            injector.Invoke(instance);
            return(instance);
        }
Ejemplo n.º 19
0
        private async Task HandleEvent(Message message)
        {
            var eventPublishData = EventPublishDataTransformer.Read(message, _serializerProvider, out var skipLocalEvents);

            if (skipLocalEvents && _serviceResolver.Resolve(eventPublishData.Service).Definition.Type == ServiceType.Local)
            {
                return;
            }

            var communicationMessage = new CommunicationMessage(message);
            await _localTransitionRunner.ReactAsync(eventPublishData, communicationMessage);
        }
Ejemplo n.º 20
0
        public object Invoke(IServiceResolver resolver, object instance, ServiceDefinition service)
        {
            Check.NotNull(resolver, nameof(resolver));
            Check.NotNull(service, nameof(service));
            if (instance is IModuleContainer)
            {
                return(instance);
            }
            var c = resolver.Resolve <IModuleContainer>();

            if (instance == null || !c.Modules.Any(m => m.Assembly == instance.GetType().Assembly) || !service.RequiredPropertyInjection())
            {
                return(instance);
            }

            var injectorFactory = resolver.Resolve <IPropertyInjectorFactory>();
            var injector        = injectorFactory.Create(instance.GetType());

            injector.Invoke(instance);
            return(instance);
        }
Ejemplo n.º 21
0
        public void Intercept(IInvocation invocation)
        {
            if (serviceImpl == null)
            {
                serviceImpl = _resolver.Resolve <Impl>();
            }

            var changable = invocation.As <IChangeProxyTarget>();

            changable.ChangeInvocationTarget(serviceImpl);
            invocation.Proceed();
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Resolve the specified service type.
 /// </summary>
 /// <returns>the service object</returns>
 public static bool TryResolve(this IServiceResolver resolver, Type type, out object value)
 {
     try
     {
         value = resolver.Resolve(type);
         return(true);
     }
     catch
     {
         value = default;
         return(false);
     }
 }
Ejemplo n.º 23
0
 public IList <IService> Resolve(IServiceResolver resolver, string protocol, TimeSpan timeout, int minServiceCountFound, int maxServiceCountFound)
 {
     resolver.ServiceFound   += new ObjectEvent <IService>(resolver_ServiceFound);
     resolver.ServiceRemoved += new ObjectEvent <IService>(resolver_ServiceRemoved);
     resolver.Resolve(protocol);
     for (int i = minServiceCountFound; i <= maxServiceCountFound; i++)
     {
         syncLock.WaitOne(timeout);
     }
     resolver.ServiceFound   -= resolver_ServiceFound;
     resolver.ServiceRemoved -= resolver_ServiceRemoved;
     return(services);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Resolve the specified service type.
 /// </summary>
 /// <typeparam name="T">service type</typeparam>
 /// <returns>the service object</returns>
 public static bool TryResolve <T>(this IServiceResolver resolver, out T value) where T : class
 {
     try
     {
         value = resolver.Resolve <T>();
         return(true);
     }
     catch
     {
         value = default;
         return(false);
     }
 }
Ejemplo n.º 25
0
        public JObject SetDb()
        {
            var data = _httpContextProxy.GetRequestBody <DBConnection>();

            _dbConfig.Set(data.Database, data.ConnectionString);
            ApplicationConfig.AppInstallStatus = AppInstallStatus.Init;
            var db = _serviceResolver.Resolve <IDBService>();

            if (db.IsConnected)
            {
                _dbConfig.Save();
                return(_responseBuilder.Success());
            }
            else
            {
                ApplicationConfig.AppInstallStatus = AppInstallStatus.DBNotSet;
                return(_responseBuilder.ServerError(new JObject
                {
                    [CommonConst.CommonField.ERR_MESSAGE] = "DB Connection error"
                }));
            }
        }
Ejemplo n.º 26
0
        private void InvokeRpcMethod(IInvocation invocation)
        {
            var rpcMethod = _serviceType.GetMethod(invocation.Method.Name, invocation.Method.GetParameters().Select(p => p.ParameterType).ToArray());

            if (rpcMethod == null)
            {
                throw new InvalidOperationException(string.Format("Cannot invoke method [{0}].", invocation.Method.Name));
            }

            var methodLocator = _fixture.Extractor.Extract(rpcMethod);

            var message = new InvokeMethodMessage()
            {
                MethodLocator   = methodLocator,
                MethodArguments = invocation.Arguments,
            };

            message.Serialize(_fixture.ArgumentEncoder);

            var service = _serviceResolver.Resolve(_serviceType, _strategy);

            _handler.Send(service.Type, service.Name, message);
        }
Ejemplo n.º 27
0
        public static object ResolveRequired(this IServiceResolver serviceResolver, Type serviceType)
        {
            if (serviceResolver == null)
            {
                throw new ArgumentNullException(nameof(serviceResolver));
            }
            var instance = serviceResolver.Resolve(serviceType);

            if (instance == null)
            {
                throw new InvalidOperationException($"No instance for type '{serviceType}' has been resolved.");
            }
            return(instance);
        }
Ejemplo n.º 28
0
        public Operation <IEnumerable <Policy> > PolicyForResource(params IAttribute[] resourceAttributes)
        => Operation.Try(async() =>
        {
            if (resourceAttributes == null || resourceAttributes.Length == 0)
            {
                return(new Policy[0].AsEnumerable());
            }

            var key = GeneratePolicyCacheKey(resourceAttributes);
            return(await _cache
                   .Set(key, false, null, _key => Operation.Try(async() =>
            {
                //generate a new one since every local variable in this lambda is captured
                var __query = _resolver.Resolve <PolicyQueries>();
                var bindRule = CreateBinder(_resolver.Resolve <IPolicyRuleResolver>());
                return (await __query
                        .FilterPoliciesByResources(resourceAttributes))
                .Select(bindRule)
                .ToArray()
                .AsEnumerable();
            }))
                   .GetOrRefresh <Policy[]>(key));
        });
Ejemplo n.º 29
0
        public async Task <JObject> Login()
        {
            try
            {
                JObject response = null;
                var     data     = _httpContextProxy.GetRequestBody <UserLoginModel>();
                if (data == null)
                {
                    response = _responseBuilder.BadRequest();
                }
                var userAccontHelper = _serviceResolver.Resolve <UserAccontHelper>();
                var user             = userAccontHelper.GetUser(data.UserName);
                if (user == null)
                {
                    response = _responseBuilder.Unauthorized();
                }
                if (userAccontHelper.ValidateUser(user, data.Password))
                {
                    ClaimsIdentity  identity  = new ClaimsIdentity(this.GetUserClaims(user), CookieAuthenticationDefaults.AuthenticationScheme);
                    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                    await _serviceResolver.Resolve <IHttpContextAccessor>().HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    response = _responseBuilder.Success();
                }
                else
                {
                    response = _responseBuilder.Unauthorized();
                }
                return(await Task.FromResult <JObject>(response));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
                return(await Task.FromResult <JObject>(_responseBuilder.ServerError()));
            }
        }
Ejemplo n.º 30
0
        private async Task HandleEvent(IModel channel, BasicDeliverEventArgs message)
        {
            var eventPublishData = DeserializePayload <EventPublishData>(message);

            if (ShouldSkipLocalEvents(message) && _serviceResolver.Resolve(eventPublishData.Service).Definition.Type == ServiceType.Local)
            {
                return;
            }

            // TODO: if there is only 1 subscriber (per this event and per this queue and connection),
            // invoke RunAsync instead of ReactAsync. The latter may even not fan out for multiple subscribers.

            await _localTransitionRunner.ReactAsync(eventPublishData, GenericCommunicatorMessage);

            channel.BasicAck(message.DeliveryTag, multiple: false);
        }
Ejemplo n.º 31
0
        public object Resolve(Type type)
        {
            ErrorLog.GetDefault(HttpContext.Current).Log(new Error(new Exception($"Resolve {type}")));

            if (type == typeof(IServerPackageRepository))
            {
                return(_serverPackageRepository);
            }

            if (type == typeof(IPackageService))
            {
                return(_packageService);
            }

            return(_serviceResolver.Resolve(type));
        }