public void Test_Core_Create_CtorTwoParams_Rev()
        {
            var fact = AutoFactory.Factory.Create <Animal>(typeof(Animal).GetTypeInfo().Assembly, TypedParameter.From(1), TypedParameter.From <Animal>(new Cat(2)));
            var dog  = fact.SeekPart(p => p.Name == "Dog");

            Assert.AreEqual(1, Animal.Dogs);
            Assert.AreEqual(2, dog.Friend.Age);
            Assert.AreEqual("Cat", dog.Friend.GetType().Name);
            Assert.AreEqual(1, Animal.CtorAgeFriend);
            Assert.AreEqual(0, Animal.CtorFriendAge);
        }
Beispiel #2
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterModule(new FiberModule <DialogTask>());

            // singleton components

            builder
            .Register(c => new ResourceManager("Microsoft.Bot.Builder.Resource.Resources", typeof(Resource.Resources).Assembly))
            .As <ResourceManager>()
            .SingleInstance();

            // every lifetime scope is driven by a message

            builder
            .Register((c, p) => p.TypedAs <IMessageActivity>())
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // make the address and cookie available for the lifetime scope

            builder
            .Register(c => Address.FromActivity(c.Resolve <IActivity>()))
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            builder
            .RegisterType <ResumptionCookie>()
            .AsSelf()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // components not marked as [Serializable]
            builder
            .RegisterType <MicrosoftAppCredentials>()
            .AsSelf()
            .SingleInstance();

            builder
            // not resolving IEqualityComparer<IAddress> from container because it's a very local policy
            // and yet too broad of an interface.  could explore using tags for registration overrides.
            .Register(c => new LocalMutualExclusion <IAddress>(new ConversationAddressComparer()))
            .As <IScope <IAddress> >()
            .SingleInstance();

            builder
            .Register(c => new ConnectorClientFactory(c.Resolve <IAddress>(), c.Resolve <MicrosoftAppCredentials>()))
            .As <IConnectorClientFactory>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeConnectorClient())
            .As <IConnectorClient>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeStateClient())
            .As <IStateClient>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new DetectChannelCapability(c.Resolve <IAddress>()))
            .As <IDetectChannelCapability>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IDetectChannelCapability>().Detect())
            .As <IChannelCapability>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <ConnectorStore, IBotDataStore <BotData> >()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <InMemoryDataStore, IBotDataStore <BotData> >()
            .SingleInstance();

            builder
            .RegisterKeyedType <CachingBotDataStore, IBotDataStore <BotData> >()
            .WithParameter((pi, c) => pi.ParameterType == typeof(CachingBotDataStoreConsistencyPolicy),
                           (pi, c) => CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency)
            .InstancePerLifetimeScope();

            builder
            .RegisterAdapterChain <IBotDataStore <BotData> >
            (
                typeof(ConnectorStore),
                typeof(CachingBotDataStore)
            )
            .InstancePerLifetimeScope();

            builder
            .RegisterType <JObjectBotData>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new DialogTaskManagerBotDataLoader(c.Resolve <JObjectBotData>(),
                                                              c.Resolve <IDialogTaskManager>()))
            .As <IBotData>()
            .InstancePerLifetimeScope();

            builder
            .Register((c, p) => new BotDataBagStream(p.TypedAs <IBotDataBag>(), p.TypedAs <string>()))
            .As <Stream>()
            .InstancePerDependency();

            builder
            .Register(c => new DialogTaskManager(DialogModule.BlobKey,
                                                 c.Resolve <JObjectBotData>(),
                                                 c.Resolve <IStackStoreFactory <DialogTask> >(),
                                                 c.Resolve <Func <IDialogStack, CancellationToken, IDialogContext> >(),
                                                 c.Resolve <IEventProducer <IActivity> >()))
            .AsSelf()
            .As <IDialogTaskManager>()
            .As <IDialogTasks>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogSystem>()
            .As <IDialogSystem>();

            builder
            .RegisterType <DialogContext>()
            .As <IDialogContext>()
            .InstancePerDependency();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();

                Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > make = (taskId, botDataBag) =>
                {
                    var stream = cc.Resolve <Stream>(TypedParameter.From(botDataBag), TypedParameter.From(taskId));
                    return(cc.Resolve <IStore <IFiberLoop <DialogTask> > >(TypedParameter.From(stream)));
                };

                return(make);
            })
            .As <Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > >()
            .InstancePerDependency();


            builder.Register(c => c.Resolve <IDialogTaskManager>().DialogTasks[0])
            .As <IDialogStack>()
            .As <IDialogTask>()
            .InstancePerLifetimeScope();

            // Scorable implementing "/deleteprofile"
            builder
            .Register(c => new Regex("^(\\s)*/deleteprofile", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
            .Keyed <Regex>(Key_DeleteProfile_Regex)
            .SingleInstance();

            builder
            .Register(c => new DeleteProfileScorable(c.Resolve <IDialogStack>(), c.Resolve <IBotData>(), c.Resolve <IBotToUser>(), c.ResolveKeyed <Regex>(Key_DeleteProfile_Regex)))
            .As <IScorable <IActivity, double> >()
            .InstancePerLifetimeScope();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();
                Func <IActivity, IResolver> make = activity =>
                {
                    var resolver = NoneResolver.Instance;
                    resolver     = new EnumResolver(resolver);
                    resolver     = new AutofacResolver(cc, resolver);
                    resolver     = new ArrayResolver(resolver,
                                                     activity,
                                                     cc.Resolve <IBotToUser>(),
                                                     cc.Resolve <IBotData>(),
                                                     cc.Resolve <IDialogSystem>());
                    resolver = new ActivityResolver(resolver);
                    resolver = new TriggerValueResolver(resolver);
                    return(resolver);
                };
                return(make);
            })
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogRouter>()
            .Keyed <IScorable <IActivity, double> >(Key_Dialog_Router)
            .InstancePerLifetimeScope();

            builder
            .RegisterType <EventQueue <IActivity> >()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <ReactiveDialogTask>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new ScoringEventLoop <double>(c.Resolve <ReactiveDialogTask>(), c.Resolve <ReactiveDialogTask>(), c.Resolve <IEventConsumer <IActivity> >(), c.ResolveKeyed <IScorable <IActivity, double> >(Key_Dialog_Router)))
            .As <IEventLoop>()
            .InstancePerLifetimeScope();

            // IPostToBot services

            builder
            .RegisterKeyedType <NullPostToBot, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <PersistentDialogTask, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <ExceptionTranslationDialogTask, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <SerializeByConversation, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <SetAmbientThreadCulture, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <PostUnhandledExceptionToUser, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <LogPostToBot, IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterAdapterChain <IPostToBot>
            (
                typeof(PersistentDialogTask),
                typeof(ExceptionTranslationDialogTask),
                typeof(SerializeByConversation),
                typeof(SetAmbientThreadCulture),
                typeof(PostUnhandledExceptionToUser),
                typeof(LogPostToBot)
            )
            .InstancePerLifetimeScope();

            // other

            builder
            .RegisterType <NullActivityLogger>()
            .AsImplementedInterfaces()
            .SingleInstance();

            builder
            .RegisterType <KeyboardCardMapper>()
            .AsImplementedInterfaces()
            .SingleInstance();

            // IBotToUser services

            builder
            .RegisterKeyedType <NullBotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <AlwaysSendDirect_BotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <MapToChannelData_BotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

            builder
            .RegisterKeyedType <LogBotToUser, IBotToUser>()
            .InstancePerLifetimeScope();

            /// <see cref="LogBotToUser"/> is composed around <see cref="MapToChannelData_BotToUser"/> is composed around
            /// <see cref="AlwaysSendDirect_BotToUser"/>.  The complexity of registering each component is pushed to a separate
            /// registration method, and each of these components are replaceable without re-registering
            /// the entire adapter chain by registering a new component with the same component key.
            builder
            .RegisterAdapterChain <IBotToUser>
            (
                typeof(AlwaysSendDirect_BotToUser),
                typeof(MapToChannelData_BotToUser),
                typeof(LogBotToUser)
            )
            .InstancePerLifetimeScope();
        }
Beispiel #3
0
 public static void Register(ILifetimeScope scope, Func <IDialog <object> > MakeRoot)
 {
     // TODO: let dialog resolve its dependencies from container
     scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
 }
Beispiel #4
0
        public IContentQuery <ContentItem> Query()
        {
            var query = _context.Resolve <IContentQuery>(TypedParameter.From <IContentManager>(this));

            return(query.ForPart <ContentItem>());
        }
        protected override void Load(ContainerBuilder builder)
        {
            // RabbitMq

            foreach (var exchange in _settings.RabbitMq.SubscribingExchanges)
            {
                builder.RegisterType <TickPricesSubscriber>()
                .AsSelf()
                .As <IStartable>()
                .As <IStopable>()
                .WithParameter("connectionString", _settings.RabbitMq.ConnectionString)
                .WithParameter("exchangeName", exchange)
                .WithParameter("suffixName", _settings.IndexName)
                .SingleInstance();
            }

            builder.RegisterType <TickPricePublisher>()
            .As <ITickPricePublisher>()
            .As <IStartable>()
            .As <IStopable>()
            .WithParameter(TypedParameter.From(_settings.RabbitMq))
            .SingleInstance();

            // Repositories

            // Blob

            builder.RegisterInstance(AzureBlobStorage.Create(_connectionString));
            builder.RegisterType <IndexHistoryBlobRepository>();

            // Tables

            builder.Register(c => new SettingsRepository(
                                 AzureTableStorage <SettingsEntity> .Create(_connectionString,
                                                                            nameof(Settings), c.Resolve <ILogFactory>())))
            .As <ISettingsRepository>()
            .SingleInstance();

            builder.Register(c => new IndexHistoryRepository(
                                 AzureTableStorage <IndexHistoryEntity> .Create(_connectionString,
                                                                                nameof(IndexHistory), c.Resolve <ILogFactory>()), c.Resolve <IndexHistoryBlobRepository>()))
            .As <IIndexHistoryRepository>()
            .SingleInstance();

            builder.Register(c => new IndexStateRepository(
                                 AzureTableStorage <IndexStateEntity> .Create(_connectionString,
                                                                              nameof(IndexState), c.Resolve <ILogFactory>())))
            .As <IIndexStateRepository>()
            .SingleInstance();

            builder.Register(c => new FirstStateAfterResetTimeRepository(
                                 AzureTableStorage <FirstStateAfterResetTimeEntity> .Create(_connectionString,
                                                                                            "FirstStateAfterResetTime", c.Resolve <ILogFactory>())))
            .As <IFirstStateAfterResetTimeRepository>()
            .SingleInstance();

            builder.Register(c => new WarningRepository(
                                 AzureTableStorage <WarningEntity> .Create(_connectionString,
                                                                           nameof(Warning), c.Resolve <ILogFactory>())))
            .As <IWarningRepository>()
            .SingleInstance();

            builder.Register(c => new ChartHistory5DRepository(
                                 AzureTableStorage <HistoryPointEntity> .Create(_connectionString,
                                                                                "ChartHistory5D", c.Resolve <ILogFactory>())))
            .As <IChartHistory5DRepository>()
            .SingleInstance();

            builder.Register(c => new ChartHistory30DRepository(
                                 AzureTableStorage <HistoryPointEntity> .Create(_connectionString,
                                                                                "ChartHistory30D", c.Resolve <ILogFactory>())))
            .As <IChartHistory30DRepository>()
            .SingleInstance();

            // Services

            builder.RegisterType <TickPricesService>()
            .As <ITickPricesService>()
            .As <ITickPriceHandler>()
            .SingleInstance();

            builder.RegisterType <CoinMarketCapClient>()
            .As <ICoinMarketCapClient>()
            .WithParameter(TypedParameter.From(new CoinMarketCap.Client.Settings(_settings.CoinMarketCapApiKey)))
            .SingleInstance();

            builder.RegisterType <CoinMarketCapService>()
            .As <ICoinMarketCapService>()
            .SingleInstance();

            builder.RegisterType <SettingsService>()
            .As <ISettingsService>()
            .WithParameter("indexTickPriceAssetPair", _settings.IndexName)
            .SingleInstance();

            builder.RegisterType <IndexCalculator>()
            .As <IIndexCalculator>()
            .As <IStartable>()
            .As <IStopable>()
            .WithParameter("indexName", _settings.IndexName)
            .WithParameter("shortIndexName", _settings.ShortIndexName)
            .WithParameter("isShortIndexEnabled", _settings.IsShortIndexEnabled)
            .WithParameter("indexCalculationInterval", _settings.IndexCalculationInterval)
            .SingleInstance();

            builder.RegisterType <StatisticsService>()
            .As <IStatisticsService>()
            .As <IIndexHandler>()
            .SingleInstance();
        }
Beispiel #6
0
        private void RegisterAppServices(ContainerBuilder builder)
        {
            builder.RegisterType <HealthService>()
            .As <IHealthService>()
            .SingleInstance();

            builder.RegisterType <StartupManager>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue))
            .As <IStartupManager>()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .SingleInstance();

            builder.RegisterType <AssetSettingsService>()
            .As <IAssetSettingsService>();

            builder.RegisterType <SupervisorMembershipService>()
            .As <ISupervisorMembershipService>();

            builder.RegisterType <CalculationService>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.LpMarkup))
            .As <ICalculationService>()
            .SingleInstance();

            builder.RegisterType <TransactionsService>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.TransactionConfirmationCount))
            .As <ITransactionsService>()
            .SingleInstance();

            builder.RegisterType <BtcTransferService>()
            .As <IBtcTransferService>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.ExpirationPeriods))
            .SingleInstance();

            builder.RegisterType <TransferService>()
            .As <ITransferService>()
            .SingleInstance();

            builder.RegisterType <NoFeeProvider>()
            .As <IFeeProvider>()
            .SingleInstance();

            builder.RegisterType <BitcoinApiClient>()
            .Keyed <IBlockchainApiClient>(BlockchainType.Bitcoin)
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.Blockchain.Bitcoin.Network))
            .SingleInstance();

            builder.RegisterType <BlockchainAddressValidator>()
            .As <IBlockchainAddressValidator>();

            builder.RegisterType <EthereumApiClient>()
            .Keyed <IBlockchainApiClient>(BlockchainType.Ethereum)
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.Blockchain.Ethereum))
            .SingleInstance();

            builder.RegisterType <EthereumIataApiClient>()
            .Keyed <IBlockchainApiClient>(BlockchainType.EthereumIata)
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.Blockchain.Ethereum))
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.RetryPolicy))
            .SingleInstance();

            builder.RegisterType <LykkeAssetsResolver>()
            .As <ILykkeAssetsResolver>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.AssetsMap));

            builder.RegisterType <MarkupService>()
            .As <IMarkupService>()
            .WithParameter("volatilityAssetPairs", _settings.CurrentValue.PayVolatilityServiceClient.AssetPairs);

            builder.RegisterType <BcnSettingsResolver>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.Blockchain))
            .As <IBcnSettingsResolver>();

            builder.RegisterType <AutoSettleSettingsResolver>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.AutoSettle))
            .As <IAutoSettleSettingsResolver>();

            builder.RegisterType <FileService>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.Merchant))
            .As <IFileService>();

            builder.RegisterType <WalletHistoryService>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.RetryPolicy))
            .As <IWalletHistoryService>();

            builder.RegisterType <WalletBalanceValidator>()
            .As <IWalletBalanceValidator>();

            builder.RegisterType <ConfirmationsService>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.PayInternalService.RetryPolicy))
            .As <IConfirmationsService>();
        }
 public static void RegisterFor(ContainerBuilder builder)
 {
     builder.RegisterType <Caching.Configuration.ConfigSetNameProvider>().Named <IConfigSetNameProvider>("CachingDecorator");
     builder.RegisterDecorator <IConfigSetNameProvider>((x, inner) => x.ResolveNamed <IConfigSetNameProvider>("CachingDecorator", TypedParameter.From(inner)), "logging").As <IConfigSetNameProvider>().SingleInstance();
 }
 public T Create <T, TU>(TU parameter)
 {
     return(Scope.Resolve <T>(TypedParameter.From(parameter)));
 }
Beispiel #9
0
        public void Register(IUnitOfWorkRegisteration unitOfWorkRegisteration)
        {
            if (IsDisposed)
            {
                throw new InvalidOperationException("UnitOfWork provider has been already disposed");
            }

            lock (UnitOfWorkCreators)
            {
                ILifetimeScope childScope = LifetimeScope.BeginLifetimeScope(containerBuilder =>
                {
                    containerBuilder.RegisterType(unitOfWorkRegisteration.UnitOfWorkCreatorType)
                    .As <IUnitOfWorkCreator>()
                    .SingleInstance();
                    unitOfWorkRegisteration.Initialize(containerBuilder);
                });

                IUnitOfWorkCreator unitOfWorkCreator = childScope.Resolve <IUnitOfWorkCreator>(TypedParameter.From(childScope));

                UnitOfWorkCreators.Add(unitOfWorkRegisteration.Name, unitOfWorkCreator);
            }
        }
Beispiel #10
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <QuoteCacheService>()
            .AsSelf()
            .As <IQuoteCacheService>()
            .As <IEventConsumer <BestPriceChangeEventArgs> >()
            .SingleInstance()
            .OnActivated(args => args.Instance.Start());

            builder.RegisterType <FplService>()
            .As <IFplService>()
            .SingleInstance();

            builder.RegisterType <TradingConditionsCacheService>()
            .AsSelf()
            .As <ITradingConditionsCacheService>()
            .SingleInstance();

            builder.RegisterType <AccountAssetsCacheService>()
            .AsSelf()
            .As <IAccountAssetsCacheService>()
            .SingleInstance();

            builder.RegisterType <AccountGroupCacheService>()
            .AsSelf()
            .As <IAccountGroupCacheService>()
            .SingleInstance();

            builder.RegisterType <AccountUpdateService>()
            .As <IAccountUpdateService>()
            .SingleInstance();

            builder.RegisterType <ValidateOrderService>()
            .As <IValidateOrderService>()
            .SingleInstance();

            builder.RegisterType <CommissionService>()
            .As <ICommissionService>()
            .SingleInstance();

            builder.RegisterType <ClientAccountService>()
            .As <IClientAccountService>()
            .SingleInstance();

            builder.RegisterType <MarketMakerMatchingEngine>()
            .As <IMarketMakerMatchingEngine>()
            .WithParameter(TypedParameter.From(MatchingEngineConstants.LykkeVuMm))
            .SingleInstance();

            builder.RegisterType <StpMatchingEngine>()
            .As <IStpMatchingEngine>()
            .WithParameter(TypedParameter.From(MatchingEngineConstants.LykkeCyStp))
            .SingleInstance();

            builder.RegisterType <TradingEngine>()
            .As <ITradingEngine>()
            .As <IEventConsumer <BestPriceChangeEventArgs> >()
            .SingleInstance();

            builder.RegisterType <MarginCallConsumer>()
            .As <IEventConsumer <MarginCallEventArgs> >()
            .As <IEventConsumer <OrderPlacedEventArgs> >()
            .As <IEventConsumer <OrderClosedEventArgs> >()
            .As <IEventConsumer <OrderCancelledEventArgs> >()
            .SingleInstance();

            builder.RegisterType <StopOutConsumer>()
            .As <IEventConsumer <StopOutEventArgs> >()
            .SingleInstance();

            builder.RegisterSource(new ContravariantRegistrationSource());
            builder.RegisterType <OrderStateConsumer>()
            .As <IEventConsumer <OrderPlacedEventArgs> >()
            .As <IEventConsumer <OrderClosedEventArgs> >()
            .As <IEventConsumer <OrderCancelledEventArgs> >()
            .As <IEventConsumer <OrderLimitsChangedEventArgs> >()
            .As <IEventConsumer <OrderClosingEventArgs> >()
            .As <IEventConsumer <OrderActivatedEventArgs> >()
            .As <IEventConsumer <OrderRejectedEventArgs> >()
            .SingleInstance();

            builder.RegisterType <TradesConsumer>()
            .As <IEventConsumer <OrderPlacedEventArgs> >()
            .As <IEventConsumer <OrderClosedEventArgs> >()
            .SingleInstance();

            builder.RegisterType <CfdCalculatorService>()
            .As <ICfdCalculatorService>()
            .SingleInstance();

            builder.RegisterType <OrderBookList>()
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <ExternalOrderBooksList>()
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <MarketMakerService>()
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <MicrographCacheService>()
            .As <IEventConsumer <BestPriceChangeEventArgs> >()
            .As <IMicrographCacheService>()
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <MarginTradingEnabledCacheService>()
            .As <IMarginTradingSettingsCacheService>()
            .SingleInstance();

            builder.RegisterType <MatchingEngineRouter>()
            .As <IMatchingEngineRouter>()
            .SingleInstance();

            builder.RegisterType <MatchingEngineRoutesCacheService>()
            .As <IMatchingEngineRoutesCacheService>()
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <AssetPairDayOffService>()
            .As <IAssetPairDayOffService>()
            .SingleInstance();

            builder.RegisterType <TelemetryPublisher>()
            .As <ITelemetryPublisher>()
            .SingleInstance();

            builder.RegisterType <ContextFactory>()
            .As <IContextFactory>()
            .SingleInstance();

            builder.Register(c =>
            {
                var settings = c.Resolve <IReloadingManager <MarginSettings> >();
                return(new RabbitMqService(c.Resolve <ILog>(), c.Resolve <IConsole>(),
                                           settings.Nested(s => s.Db.StateConnString), settings.CurrentValue.Env));
            })
            .As <IRabbitMqService>()
            .SingleInstance();

            builder.RegisterType <DayOffSettingsService>()
            .As <IDayOffSettingsService>()
            .As <IStartable>()
            .SingleInstance();

            builder.RegisterType <AlertSeverityLevelService>()
            .As <IAlertSeverityLevelService>()
            .SingleInstance();

            builder.RegisterInstance(_riskInformingSettings)
            .As <IReloadingManager <RiskInformingSettings> >()
            .SingleInstance();

            builder.RegisterType <MarginTradingEnablingService>()
            .As <IMarginTradingEnablingService>()
            .As <IStartable>()
            .SingleInstance();

            builder.RegisterType <OvernightSwapService>()
            .As <IOvernightSwapService>()
            .SingleInstance()
            .OnActivated(args => args.Instance.Start());
        }
Beispiel #11
0
        public static async Task VerifyScript(ILifetimeScope container, Func <IDialog <object> > makeRoot, bool proactive, StreamReader stream, Action <IDialogStack, string> extraCheck, string[] expected, string locale)
        {
            var toBot = DialogTestBase.MakeTestMessage();

            if (!string.IsNullOrEmpty(locale))
            {
                toBot.Locale = locale;
            }

            string input, label;
            int    current = 0;

            while ((input = ReadLine(stream, out label)) != null)
            {
                var adapter = new TestAdapter();
                await adapter.ProcessActivity((Activity)toBot, async (ctx) =>
                {
                    using (var scope = DialogModule.BeginLifetimeScope(container, ctx))
                    {
                        var task  = scope.Resolve <IPostToBot>();
                        var queue = adapter.ActiveQueue;

                        Action <IDialogStack> check = (stack) =>
                        {
                            var count = int.Parse((proactive && current == 0) ? input : stream.ReadLine());
                            Assert.AreEqual(count, queue.Count);
                            for (var i = 0; i < count; ++i)
                            {
                                var toUser      = queue.Dequeue();
                                var expectedOut = ReadLine(stream, out label);
                                if (label == "ToUserText")
                                {
                                    Assert.AreEqual(expectedOut, JsonConvert.SerializeObject(toUser.Text));
                                }
                                else
                                {
                                    Assert.AreEqual(expectedOut, JsonConvert.SerializeObject(toUser.Attachments));
                                }
                            }

                            extraCheck?.Invoke(stack, ReadLine(stream, out label));
                        };

                        Func <IDialog <object> > scriptMakeRoot = () =>
                        {
                            return(makeRoot().Do(async(context, value) => context.PrivateConversationData.SetValue("result", JsonConvert.SerializeObject(await value))));
                        };
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(scriptMakeRoot));

                        if (proactive && current == 0)
                        {
                            var loop = scriptMakeRoot().Loop();
                            var data = scope.Resolve <IBotData>();
                            await data.LoadAsync(CancellationToken.None);
                            var stack = scope.Resolve <IDialogTask>();
                            stack.Call(loop, null);
                            await stack.PollAsync(CancellationToken.None);
                            check(stack);
                            input = ReadLine(stream, out label);
                        }

                        if (input.StartsWith("\""))
                        {
                            try
                            {
                                toBot.Text = input.Substring(1, input.Length - 2);
                                Assert.IsTrue(current < expected.Length && toBot.Text == expected[current++]);
                                await task.PostAsync(toBot, CancellationToken.None);
                                var data = scope.Resolve <IBotData>();
                                await data.LoadAsync(CancellationToken.None);
                                var stack = scope.Resolve <IDialogStack>();
                                check(stack);
                            }
                            catch (Exception e)
                            {
                                Assert.AreEqual(ReadLine(stream, out label), e.Message);
                            }
                        }
                        else if (label.ToLower().StartsWith("result"))
                        {
                            var data = scope.Resolve <IBotData>();
                            await data.LoadAsync(CancellationToken.None);
                            string result;
                            Assert.IsTrue(data.PrivateConversationData.TryGetValue("result", out result));
                            Assert.AreEqual(input.Trim(), result);
                        }
                    }
                });
            }
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>()
            .SingleInstance();

            var rabbitMqSettings = new ConnectionFactory
            {
                Uri = new Uri(_settings.Cqrs.RabbitConnString)
            };
            var rabbitMqEndpoint = rabbitMqSettings.Endpoint.ToString();

            builder.RegisterType <StartupManager>().As <IStartupManager>();
            builder.RegisterType <ShutdownManager>().As <IShutdownManager>();

            builder.RegisterType <ExecutionQueueReader>()
            .WithParameter(TypedParameter.From(_settings.Cqrs.RabbitConnString))
            .WithParameter(TypedParameter.From(_settings.WalletIdsToLog))
            .WithParameter(new NamedParameter("prefetchCount", _settings.RabbitPrefetchCount))
            .WithParameter(new NamedParameter("batchCount", _settings.PostgresOrdersBatchSize))
            .SingleInstance();

            builder.RegisterType <OrderEventQueueReader>()
            .WithParameter(TypedParameter.From(_settings.Cqrs.RabbitConnString))
            .WithParameter(TypedParameter.From(_settings.WalletIdsToLog))
            .WithParameter(new NamedParameter("prefetchCount", _settings.RabbitPrefetchCount))
            .WithParameter(new NamedParameter("batchCount", _settings.PostgresOrdersBatchSize))
            .SingleInstance();

            builder.RegisterType <CashInProjection>();
            builder.RegisterType <CashOutProjection>();
            builder.RegisterType <CashTransferProjection>();
            builder.RegisterType <TransactionHashProjection>();

            builder.RegisterType <EthereumCommandHandler>();
            builder.RegisterType <ForwardWithdrawalCommandHandler>();

            builder.Register(ctx =>
            {
                var logFactory      = ctx.Resolve <ILogFactory>();
                var messagingEngine = new MessagingEngine(
                    logFactory,
                    new TransportResolver(
                        new Dictionary <string, TransportInfo>
                {
                    {
                        "RabbitMq",
                        new TransportInfo(
                            rabbitMqEndpoint,
                            rabbitMqSettings.UserName,
                            rabbitMqSettings.Password, "None", "RabbitMq")
                    }
                }),
                    new RabbitMqTransportFactory(logFactory));
                var cqrsEngine = CreateEngine(ctx, messagingEngine, logFactory);
                cqrsEngine.StartPublishers();
                return(cqrsEngine);
            })
            .As <ICqrsEngine>()
            .AutoActivate()
            .SingleInstance();
        }
Beispiel #13
0
        public void FromWorksJustLikeTheConstructor()
        {
            var param = TypedParameter.From(new B());

            Assert.Same(typeof(B), param.Type);
        }
        protected override void Load(ContainerBuilder builder)
        {
            Messaging.Serialization.MessagePackSerializerFactory.Defaults.FormatterResolver = MessagePack.Resolvers.ContractlessStandardResolver.Instance;
            var rabbitMqSettings = new RabbitMQ.Client.ConnectionFactory
            {
                Uri = _settings.CurrentValue.SagasRabbitMqSettings.ConnectionString
            };

            builder.Register(context => new AutofacDependencyResolver(context)).As <IDependencyResolver>().SingleInstance();

            builder.Register(c =>
                             new MessagingEngine(_log,
                                                 new TransportResolver(new Dictionary <string, TransportInfo>
            {
                { "RabbitMq", new TransportInfo(rabbitMqSettings.Endpoint.ToString(), rabbitMqSettings.UserName, rabbitMqSettings.Password, "None", "RabbitMq") }
            }),
                                                 new RabbitMqTransportFactory()))
            .As <IMessagingEngine>();

            builder.RegisterType <ConfirmationCommandHandler>();

            builder.RegisterType <AssetsProjection>();
            builder.RegisterType <HistoryExportProjection>();
            builder.RegisterType <OperationsProjection>();
            builder.RegisterType <MarketDataProjection>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.CacheSettings.MarketDataCacheInterval));

            var protobufEndpointResolver = new RabbitMqConventionEndpointResolver(
                "RabbitMq",
                SerializationFormat.ProtoBuf,
                environment: "lykke",
                exclusiveQueuePostfix: _env);

            builder.Register(ctx =>
            {
                const string defaultRoute = "self";

                var engine = new CqrsEngine(
                    _log,
                    ctx.Resolve <IDependencyResolver>(),
                    ctx.Resolve <IMessagingEngine>(),
                    new DefaultEndpointProvider(),
                    true,
                    Register.DefaultEndpointResolver(new RabbitMqConventionEndpointResolver(
                                                         "RabbitMq",
                                                         SerializationFormat.MessagePack,
                                                         environment: "lykke",
                                                         exclusiveQueuePostfix: _env)),

                    Register.BoundedContext(WampHostBoundedContext.Name)
                    .ListeningEvents(
                        typeof(AssetCreatedEvent),
                        typeof(AssetUpdatedEvent),
                        typeof(AssetPairCreatedEvent),
                        typeof(AssetPairUpdatedEvent))
                    .From(BoundedContexts.Assets).On(defaultRoute)
                    .WithProjection(typeof(AssetsProjection), BoundedContexts.Assets)
                    .ListeningEvents(
                        typeof(ClientHistoryExportedEvent))
                    .From(HistoryExportBuilderBoundedContext.Name).On(defaultRoute)
                    .WithProjection(typeof(HistoryExportProjection), HistoryExportBuilderBoundedContext.Name)
                    .ListeningEvents(typeof(OperationFailedEvent), typeof(OperationConfirmedEvent), typeof(OperationCompletedEvent), typeof(OperationCorruptedEvent))
                    .From(OperationsBoundedContext.Name).On(defaultRoute)
                    .WithProjection(typeof(OperationsProjection), OperationsBoundedContext.Name)
                    .ListeningEvents(typeof(MarketDataChangedEvent))
                    .From(MarketDataBoundedContext.Name).On(defaultRoute)
                    .WithProjection(typeof(MarketDataProjection), MarketDataBoundedContext.Name)
                    .ListeningCommands(typeof(RequestConfirmationCommand)).On("commands")
                    .WithEndpointResolver(protobufEndpointResolver)
                    .WithCommandsHandler <ConfirmationCommandHandler>()
                    );
                engine.StartPublishers();
                return(engine);
            })
            .As <ICqrsEngine>()
            .SingleInstance()
            .AutoActivate();
        }
Beispiel #15
0
        public MainWindowViewModel(ILifetimeScope lifetimeScope, IUIDispatcher dispatcher,
                                   IOperationManager operationManager, LocLocalizer localizer, IDialogCoordinator dialogCoordinator,
                                   AppConfig config, IDialogFactory dialogFactory, IViewModel <CenterViewModel> model,
                                   IMainWindowCoordinator mainWindowCoordinator, ProjectFileWorkspace workspace)
            : base(lifetimeScope, dispatcher)
        {
            this.Receive <IncommingEvent>(e => e.Action());

            var last             = new RxVar <ProjectFile?>(null);
            var loadingOperation = new RxVar <OperationController?>(null);

            var self = Self;

            CenterView = this.RegisterViewModel(nameof(CenterView), model);
            workspace.Source.ProjectReset.RespondOn(null, pr => last.Value = pr.ProjectFile);

            #region Restarting

            Start.Subscribe(_ =>
            {
                if (last != null)
                {
                    Self.Tell(last);
                }
            });
            this.Receive <ProjectFile>(workspace.Reset);

            #endregion

            #region Operation Manager

            RunningOperations = RegisterProperty <IEnumerable <RunningOperation> >(nameof(RunningOperations))
                                .WithDefaultValue(operationManager.RunningOperations);
            RenctFiles = RegisterProperty <RenctFilesCollection>(nameof(RenctFiles))
                         .WithDefaultValue(new RenctFilesCollection(config, s => self.Tell(new InternlRenctFile(s))));

            NewCommad.WithExecute(operationManager.Clear, operationManager.ShouldClear()).ThenRegister("ClearOp");
            NewCommad.WithExecute(operationManager.CompledClear, operationManager.ShouldCompledClear())
            .ThenRegister("ClearAllOp");

            #endregion

            #region Save As

            IObservable <UpdateSource> SaveAsProject()
            {
                var targetFile = dialogFactory.ShowSaveFileDialog(null, true, false, true, "transp", true,
                                                                  localizer.OpenFileDialogViewDialogFilter, true, true, localizer.MainWindowMainMenuFileSaveAs,
                                                                  Directory.GetCurrentDirectory());

                return(targetFile.NotEmpty()
                       .SelectMany(CheckSourceOk)
                       .Where(d => d.Item1)
                       .Select(r => new UpdateSource(r.Item2)));
            }

            async Task <(bool, string)> CheckSourceOk(string source)
            {
                if (!string.IsNullOrWhiteSpace(source))
                {
                    return(true, source);
                }
                await UICall(()
                             => dialogCoordinator.ShowMessage(localizer.CommonError,
                                                              localizer.MainWindowModelLoadProjectSourceEmpty !));

                return(false, source);
            }

            NewCommad.WithCanExecute(last.Select(pf => pf != null && !pf.IsEmpty))
            .WithFlow(ob => ob.SelectMany(_ => SaveAsProject())
                      .ToModel(CenterView))
            .ThenRegister("SaveAs");

            #endregion

            #region Open File

            IDisposable NewProjectFile(IObservable <SourceSelected> source) => source
            .SelectMany(SourceSelectedFunc)
            .NotNull()
            .ObserveOnSelf()
            .Select(ProjectLoaded)
            .ToModel(CenterView !);


            this.Receive <InternlRenctFile>(o => OpentFileSource(o.File));

            IObservable <LoadedProjectFile?> SourceSelectedFunc(SourceSelected s)
            {
                if (s.Mode != OpenFileMode.OpenExistingFile)
                {
                    return(NewFileSource(s.Source));
                }
                OpentFileSource(s.Source);
                return(Observable.Return <LoadedProjectFile?>(null));
            }

            void OpentFileSource(string?rawSource)
            {
                Observable.Return(rawSource)
                .NotEmpty()
                .SelectMany(CheckSourceOk)
                .Select(p => p.Item2)
                .Do(_ => mainWindowCoordinator.IsBusy = true)
                .SelectMany(source => operationManager
                            .StartOperation(string.Format(localizer.MainWindowModelLoadProjectOperation,
                                                          Path.GetFileName(source)))
                            .Do(op => loadingOperation !.Value = op)
                            .Select(operationController => (operationController, source)))
                .Do(_ =>
                {
                    if (!workspace.ProjectFile.IsEmpty)
                    {
                        workspace.ProjectFile.Operator.Tell(ForceSave.Force(workspace.ProjectFile));
                    }
                })
                .ObserveOnSelf()
                .Subscribe(pair
                           => ProjectFile.BeginLoad(Context, pair.operationController.Id, pair.source,
                                                    "Project_Operator"));
            }

            SupplyNewProjectFile?ProjectLoaded(LoadedProjectFile obj)
            {
                try
                {
                    if (loadingOperation !.Value != null)
                    {
                        if (obj.Ok)
                        {
                            loadingOperation.Value.Compled();
                        }
                        else
                        {
                            loadingOperation.Value.Failed(obj.ErrorReason?.Message ?? localizer.CommonError);
                            return(null);
                        }
                    }

                    loadingOperation.Value = null;
                    if (obj.Ok)
                    {
                        RenctFiles !.Value.AddNewFile(obj.ProjectFile.Source);
                    }

                    last !.Value = obj.ProjectFile;

                    return(new SupplyNewProjectFile(obj.ProjectFile));
                }
                finally
                {
                    mainWindowCoordinator.IsBusy = false;
                }
            }

            NewCommad.WithCanExecute(loadingOperation.Select(oc => oc == null))
            .WithFlow(obs => NewProjectFile(obs.Dialog(this, TypedParameter.From(OpenFileMode.OpenExistingFile))
                                            .Of <IOpenFileDialog, string?>()
                                            .Select(s => SourceSelected.From(s, OpenFileMode.OpenExistingFile))))
            .ThenRegister("OpenFile");

            NewProjectFile(Receive <SourceSelected>()).DisposeWith(this);
            Receive <LoadedProjectFile>(ob => ob.Select(ProjectLoaded).ToModel(CenterView !));

            #endregion

            #region New File

            IObservable <LoadedProjectFile?> NewFileSource(string?source)
            {
                source ??= string.Empty;
                var data = new LoadedProjectFile(string.Empty,
                                                 ProjectFile.NewProjectFile(Context, source, "Project_Operator"), null, true);

                if (File.Exists(source))
                {
                    //TODO NewFile Filog Message
                    var result = UICall(async()
                                        => await dialogCoordinator.ShowMessage(localizer.CommonError !, "", null));

                    return(result.Where(b => b == true).Do(_ => mainWindowCoordinator.IsBusy = true).Select(_ => data));
                }

                mainWindowCoordinator.IsBusy = true;
                return(Observable.Return(data));
            }

            NewCommad.WithCanExecute(loadingOperation.Select(oc => oc == null))
            .WithFlow(obs => obs.Dialog(this, TypedParameter.From(OpenFileMode.OpenNewFile))
                      .Of <IOpenFileDialog, string?>()
                      .Select(s => SourceSelected.From(s, OpenFileMode.OpenNewFile))
                      .ToSelf())
            .ThenRegister("NewFile");

            #endregion

            #region Analyzing

            AnalyzerEntries = this.RegisterUiCollection <AnalyzerEntry>(nameof(AnalyzerEntries))
                              .BindToList(out var analyterList);

            var builder = new AnalyzerEntryBuilder(localizer);

            void IssuesChanged(IssuesEvent obj)
            {
                analyterList.Edit(l =>
                {
                    var(ruleName, issues) = obj;
                    l.Remove(AnalyzerEntries.Where(e => e.RuleName == ruleName));
                    l.AddRange(issues.Select(builder.Get));
                });
            }

            this.RespondOnEventSource(workspace.Analyzer.Issues, IssuesChanged);

            #endregion

            #region Build

            var buildModel = lifetimeScope.Resolve <IViewModel <BuildViewModel> >();
            buildModel.InitModel(Context, "Build-View");

            BuildModel = RegisterProperty <IViewModel <BuildViewModel> >(nameof(BuildModel)).WithDefaultValue(buildModel);

            #endregion
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule <IoCDataModule>();

            // MainStage
            {
                // Register keyed main View/Presenter
                builder.RegisterType <MainStageView>().As <IMainStageView>().Keyed <IStageView>(Key.MainStage).InstancePerLifetimeScope();
                // Parameters must be specified because dependencies have multiple types registered
                builder.RegisterType <MainStagePresenter>().As <IStagePresenter>().Keyed <IStagePresenter>(Key.MainStage)
                .WithParameters(new[] {
                    // Resolve IStageView keyed with Key.Main
                    ResolvedParameter.ForKeyed <IMainStageView>(Key.MainStage),
                    // Resolve IPresenter factory keyed with PresenterType.Order
                    ResolvedParameter.ForKeyed <Func <IPresenter> >(Key.Order),
                    // Resolve IDatabaseInitializer keyed with Database.Orders
                    ResolvedParameter.ForKeyed <IDatabaseInitializer>(Database.Orders)
                }).InstancePerLifetimeScope();
                // Register ToolStripRenderer for MainStageView
                builder.RegisterInstance(new ToolStripProfessionalRenderer(new MenuColorTable())).As <ToolStripRenderer>();
            }

            // ChildStage
            {
                // Register keyed child View/Presenter
                builder.RegisterType <ChildStageView>().As <IStageView>().Keyed <IStageView>(Key.ChildStage).InstancePerLifetimeScope();
                // Parameters must be specified because dependencies have multiple types registered
                builder.RegisterType <ChildStagePresenter>().As <IStagePresenter>().AsSelf().Keyed <IStagePresenter>(Key.ChildStage)
                .WithParameters(new[] {
                    // Resolve IStageView keyed with Key.ChildStage
                    ResolvedParameter.ForKeyed <IStageView>(Key.ChildStage),
                    // Resolve IPresenter factory keyed with PresenterType.Login
                    // Parameter name must be specified as ChildStagePresenter takes 2 different IPresenter factories
                    new ResolvedParameter(
                        (pi, ctx) => pi.ParameterType == typeof(Func <Action, IPresenter>) && pi.Name == "loginPresenterFactory",
                        (pi, ctx) => ctx.ResolveKeyed <Func <Action, IPresenter> >(Key.Login)
                        ),
                    // Resolve IPresenter factory keyed with PresenterType.Register
                    // Parameter name must be specified as ChildStagePresenter takes 2 different IPresenter factories
                    new ResolvedParameter(
                        (pi, ctx) => pi.ParameterType == typeof(Func <Action, IPresenter>) && pi.Name == "registerPresenterFactory",
                        (pi, ctx) => ctx.ResolveKeyed <Func <Action, IPresenter> >(Key.Register)
                        ),
                    // Resolve IDatabaseInitializer keyed with Database.Orders
                    ResolvedParameter.ForKeyed <IDatabaseInitializer>(Database.Users)
                }).InstancePerLifetimeScope();
                // Register an IStagePresenter factory that returns a child stage Presenter with the InitialView property set
                builder.Register <Func <ChildStageViewType, Action, IStagePresenter> >(context =>
                {
                    var cc = context.Resolve <IComponentContext>();
                    return((initialView, action) =>
                    {
                        var presenter = cc.ResolveKeyed <IStagePresenter>(Key.ChildStage, TypedParameter.From(action)) as ChildStagePresenter;
                        presenter.InitialView = initialView;
                        return presenter;
                    });
                });
            }

            // Order
            {
                // Register order View/Presenter keyed with PresenterType.Order
                builder.RegisterType <OrderView>().As <IOrderView>();
                builder.RegisterType <OrderPresenter>().As <IPresenter>().Keyed <IPresenter>(Key.Order).WithParameter(ResolvedParameter.ForKeyed <IStagePresenter>(Key.MainStage));
                // Register IPresenter factory which returns IPresenter keyed with PresenterType.Order
                builder.Register <Func <IPresenter> >(context =>
                {
                    var cc = context.Resolve <IComponentContext>();
                    return(() => cc.ResolveKeyed <IPresenter>(Key.Order));
                }).Keyed <Func <IPresenter> >(Key.Order);
            }

            // Item
            {
                // Register item View/Presenter
                builder.RegisterType <ItemView>().As <IItemView>();
                builder.RegisterType <ItemPresenter>().As <IPresenter>().Keyed <IPresenter>(Key.Item).WithParameter(ResolvedParameter.ForKeyed <IStagePresenter>(Key.MainStage));
                // Register ItemPresenter factory
                builder.Register <Func <IReadOnlyList <Item>, Action, IPresenter> >(context =>
                {
                    var cc = context.Resolve <IComponentContext>();
                    return((items, action) => cc.ResolveKeyed <IPresenter>(Key.Item, TypedParameter.From(items), TypedParameter.From(action)));
                });
            }

            // Login
            {
                // Register login View/Presenter keyed with PresenterType.Login
                builder.RegisterType <LoginView>().As <ILoginView>();
                builder.RegisterType <LoginPresenter>().As <IPresenter>().Keyed <IPresenter>(Key.Login).WithParameter(ResolvedParameter.ForKeyed <IStagePresenter>(Key.ChildStage));
                // Register IPresenter factory which returns IPresenter keyed with PresenterType.Login
                builder.Register <Func <Action, IPresenter> >(context =>
                {
                    var cc = context.Resolve <IComponentContext>();
                    return(action => cc.ResolveKeyed <IPresenter>(Key.Login, TypedParameter.From(action)));
                }).Keyed <Func <Action, IPresenter> >(Key.Login);
            }

            // Register
            {
                // Register register View/Presenter keyed with PresenterType.Register
                builder.RegisterType <RegisterView>().As <IRegisterView>();
                builder.RegisterType <RegisterPresenter>().As <IPresenter>().Keyed <IPresenter>(Key.Register).WithParameter(ResolvedParameter.ForKeyed <IStagePresenter>(Key.ChildStage));
                // Register IPresenter factory which returns IPresenter keyed with PresenterType.Register
                builder.Register <Func <Action, IPresenter> >(context =>
                {
                    var cc = context.Resolve <IComponentContext>();
                    return(action => cc.ResolveKeyed <IPresenter>(Key.Register, TypedParameter.From(action)));
                }).Keyed <Func <Action, IPresenter> >(Key.Register);
            }

            // Mappers
            {
                builder.RegisterType <DtoMapper>().As <IDtoMapper>().InstancePerLifetimeScope();
                builder.RegisterType <VmMapper>().As <IVmMapper>().InstancePerLifetimeScope();
            }

            // Filtering
            {
                builder.RegisterType <OrderFilterer>().As <IOrderFilterer>().InstancePerLifetimeScope();
                builder.RegisterType <ItemFilterer>().As <IItemFilterer>().InstancePerLifetimeScope();

                // Any/All filter strategies
                {
                    builder.RegisterType <FilterAnyStrategy>().As <IAnyAllFilterModeStrategy>().Keyed <IAnyAllFilterModeStrategy>(AnyAllFilterMode.Any).InstancePerLifetimeScope();
                    builder.RegisterType <FilterAllStrategy>().As <IAnyAllFilterModeStrategy>().Keyed <IAnyAllFilterModeStrategy>(AnyAllFilterMode.All).InstancePerLifetimeScope();
                    // Register an IAnyAllFilterModeStrategy factory which returns the strategy keyed with the AnyAllFilterMode provided
                    builder.Register <Func <AnyAllFilterMode, IAnyAllFilterModeStrategy> >(context =>
                    {
                        var cc = context.Resolve <IComponentContext>();
                        return(mode => cc.ResolveKeyed <IAnyAllFilterModeStrategy>(mode));
                    });
                }

                // Min/Max filter strategies
                {
                    builder.RegisterType <OrderItemCountFilterMaxStrategy>().As <IMinMaxFilterModeStrategy <Order> >().Keyed <IMinMaxFilterModeStrategy <Order> >(MinMaxFilterMode.Max);
                    builder.RegisterType <OrderItemCountFilterMinStrategy>().As <IMinMaxFilterModeStrategy <Order> >().Keyed <IMinMaxFilterModeStrategy <Order> >(MinMaxFilterMode.Min);
                    // Register an IMinMaxFilterModeStrategy factory which returns the strategy keyed with the MinMaxFilterMode provided
                    builder.Register <Func <string, MinMaxFilterMode, IMinMaxFilterModeStrategy <Order> > >(context =>
                    {
                        var cc = context.Resolve <IComponentContext>();
                        return((countType, mode) =>
                        {
                            int getItemCountProperty(Order order) => countType switch
                            {
                                nameof(Order.TotalCount) => order.TotalCount,
                                nameof(Order.UniqueCount) => order.UniqueCount,
                                _ => default
                            };
                            return cc.ResolveKeyed <IMinMaxFilterModeStrategy <Order> >(mode, TypedParameter.From <Func <Order, int> >(getItemCountProperty));
                        });
                    });

                    builder.RegisterType <ItemCountFilterMaxStrategy>().As <IMinMaxFilterModeStrategy <ItemVm> >().Keyed <IMinMaxFilterModeStrategy <ItemVm> >(MinMaxFilterMode.Max);
                    builder.RegisterType <ItemCountFilterMinStrategy>().As <IMinMaxFilterModeStrategy <ItemVm> >().Keyed <IMinMaxFilterModeStrategy <ItemVm> >(MinMaxFilterMode.Min);
                    // Register an IMinMaxFilterModeStrategy factory which returns the strategy keyed with the MinMaxFilterMode provided
                    builder.Register <Func <MinMaxFilterMode, IMinMaxFilterModeStrategy <ItemVm> > >(context =>
                    {
                        var cc = context.Resolve <IComponentContext>();
                        return(mode => cc.ResolveKeyed <IMinMaxFilterModeStrategy <ItemVm> >(mode));
                    });
                }

                // Strict/Loose filter strategies
                {
                    builder.RegisterType <OrderSearchFilterStrictStrategy>().As <IStrictLooseFilterModeStrategy <Order> >().Keyed <IStrictLooseFilterModeStrategy <Order> >(StrictLooseFilterMode.Strict);
                    builder.RegisterType <OrderSearchFilterLooseStrategy>().As <IStrictLooseFilterModeStrategy <Order> >().Keyed <IStrictLooseFilterModeStrategy <Order> >(StrictLooseFilterMode.Loose);

                    builder.Register <Func <string, StrictLooseFilterMode, IStrictLooseFilterModeStrategy <Order> > >(context =>
                    {
                        var cc = context.Resolve <IComponentContext>();
                        return((searchType, mode) =>
                        {
                            string getOrderProperty(Order order) => searchType switch
                            {
                                nameof(Order.Id) => order.Id.ToString(),
                                nameof(Order.BuyerName) => order.BuyerName,
                                _ => default
                            };
                            return cc.ResolveKeyed <IStrictLooseFilterModeStrategy <Order> >(mode, TypedParameter.From <Func <Order, string> >(getOrderProperty));
                        });
                    });

                    builder.RegisterType <ItemSearchFilterStrictStrategy>().As <IStrictLooseFilterModeStrategy <ItemVm> >().Keyed <IStrictLooseFilterModeStrategy <ItemVm> >(StrictLooseFilterMode.Strict);
                    builder.RegisterType <ItemSearchFilterLooseStrategy>().As <IStrictLooseFilterModeStrategy <ItemVm> >().Keyed <IStrictLooseFilterModeStrategy <ItemVm> >(StrictLooseFilterMode.Loose);

                    builder.Register <Func <string, StrictLooseFilterMode, IStrictLooseFilterModeStrategy <ItemVm> > >(context =>
                    {
                        var cc = context.Resolve <IComponentContext>();
                        return((searchType, mode) =>
                        {
                            string getItemProperty(ItemVm item) => searchType switch
                            {
                                nameof(ItemVm.Number) => item.Number,
                                nameof(ItemVm.InventoryId) => item.InventoryId.ToString(),
                                nameof(ItemVm.Name) => item.Name,
                                _ => default
                            };
                            return cc.ResolveKeyed <IStrictLooseFilterModeStrategy <ItemVm> >(mode, TypedParameter.From <Func <ItemVm, string> >(getItemProperty));
                        });
                    });
                }
            }
        }
Beispiel #17
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterInstance(_settings.ProcessRequestJob)
            .SingleInstance();

            builder.RegisterInstance(_settings.NinjaServiceClient)
            .SingleInstance();

            builder.RegisterInstance(_log)
            .As <ILog>()
            .SingleInstance();

            builder.RegisterType <HealthService>()
            .As <IHealthService>()
            .SingleInstance()
            .WithParameter(TypedParameter.From(TimeSpan.FromSeconds(30)));

            var bitcoinAggRepository = new BitcoinAggRepository(
                new AzureTableStorage <BitcoinAggEntity>(
                    _settings.ProcessRequestJob.Db.MerchantWalletConnectionString, "BitcoinAgg",
                    null),
                new AzureTableStorage <BitcoinHeightEntity>(
                    _settings.ProcessRequestJob.Db.MerchantWalletConnectionString, "BitcoinHeight",
                    null));

            builder.RegisterInstance(bitcoinAggRepository)
            .As <IBitcoinAggRepository>()
            .SingleInstance();

            var merchantPayRequestRepository =
                new MerchantPayRequestRepository(
                    new AzureTableStorage <MerchantPayRequest>(_settings.ProcessRequestJob.Db.MerchantWalletConnectionString, "MerchantPayRequest", null));

            builder.RegisterInstance(merchantPayRequestRepository)
            .As <IMerchantPayRequestRepository>()
            .SingleInstance();

            var merchantOrderRequestRepository =
                new MerchantOrderRequestRepository(
                    new AzureTableStorage <MerchantOrderRequest>(_settings.ProcessRequestJob.Db.MerchantWalletConnectionString, "MerchantOrderRequest", null));

            builder.RegisterInstance(merchantOrderRequestRepository)
            .As <IMerchantOrderRequestRepository>()
            .SingleInstance();

            builder.RegisterType <BitcoinApi>()
            .As <IBitcoinApi>()
            .SingleInstance()
            .WithParameter(TypedParameter.From(new Uri(_settings.BitcoinApiClient.ServiceUrl)));

            builder.RegisterType <LykkePayServiceStoreRequestMicroService>()
            .As <ILykkePayServiceStoreRequestMicroService>()
            .SingleInstance()
            .WithParameter(TypedParameter.From(new Uri(_settings.ProcessRequestJob.Services.LykkePayServiceStoreRequestMicroService)));

            builder.RegisterType <LykkePayServiceGenerateAddressMicroService>()
            .As <ILykkePayServiceGenerateAddressMicroService>()
            .SingleInstance()
            .WithParameter(TypedParameter.From(new Uri(_settings.ProcessRequestJob.Services.LykkePayServiceGenerateAddressMicroService)));

            builder.RegisterType <ProcessRequest>()
            .As <IProcessRequest>()
            .SingleInstance();

            var client = new RPCClient(
                new NetworkCredential(_settings.ProcessRequestJob.Rpc.UserName,
                                      _settings.ProcessRequestJob.Rpc.Password),
                new Uri(_settings.ProcessRequestJob.Rpc.Url), Network.GetNetwork(_settings.ProcessRequestJob.Rpc.Network));

            builder.RegisterInstance(client)
            .As <RPCClient>()
            .SingleInstance();

            //builder.RegisterType<BalanceChangeHandler>()
            //    .As<IBalanceChangeHandler>()
            //    .As<IStartable>()
            //    .SingleInstance();

            builder.Populate(_services);
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <RegistrationService>()
            .As <IRegistrationService>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Constants.TokenSymbol))
            .SingleInstance();

            builder.RegisterType <AuthService>()
            .As <IAuthService>()
            .SingleInstance();

            builder.Register(context =>
            {
                var connectionMultiplexer = ConnectionMultiplexer.Connect(_appSettings.CurrentValue.CustomerManagementService.Redis.ConnString);
                return(connectionMultiplexer);
            }).As <IConnectionMultiplexer>().SingleInstance();
            builder.RegisterType <EmailVerificationService>()
            .As <IEmailVerificationService>()
            .SingleInstance()
            .WithParameter(
                "verificationThankYouEmailTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.VerificationThankYouEmailTemplateId)
            .WithParameter(
                "verificationThankYouEmailSubjectTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.VerificationThankYouEmailSubjectTemplateId)
            .WithParameter(
                "verificationEmailTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.VerificationEmailTemplateId)
            .WithParameter(
                "verificationEmailSubjectTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.VerificationEmailSubjectTemplateId)
            .WithParameter(
                "verificationEmailVerificationLink",
                _appSettings.CurrentValue.CustomerManagementService.VerificationEmailVerificationLink);

            builder.RegisterType <PasswordResetService>()
            .As <IPasswordResetService>()
            .WithParameter(
                "passwordResetEmailTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.PasswordResetEmailTemplateId)
            .WithParameter(
                "passwordResetEmailSubjectTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.PasswordResetEmailSubjectTemplateId)
            .WithParameter(
                "passwordResetEmailVerificationLinkTemplate",
                _appSettings.CurrentValue.CustomerManagementService.PasswordResetEmailVerificationLinkTemplate)
            .WithParameter(
                "passwordSuccessfulResetEmailTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.PasswordSuccessfulResetEmailTemplateId)
            .WithParameter(
                "passwordSuccessfulResetEmailSubjectTemplateId",
                _appSettings.CurrentValue.CustomerManagementService.PasswordSuccessfulResetEmailSubjectTemplateId)
            .SingleInstance();

            builder.RegisterType <CustomersService>()
            .As <ICustomersService>()
            .SingleInstance()
            .WithParameter("passwordSuccessfulChangeEmailTemplateId",
                           _appSettings.CurrentValue.CustomerManagementService.PasswordSuccessfulChangeEmailTemplateId)
            .WithParameter("passwordSuccessfulChangeEmailSubjectTemplateId",
                           _appSettings.CurrentValue.CustomerManagementService.PasswordSuccessfulChangeEmailSubjectTemplateId)
            .WithParameter("getCustomerBlockStatusBatchMaxValue",
                           _appSettings.CurrentValue.CustomerManagementService.GetCustomerBlockStatusBatchRequestMaxSize)
            .WithParameter("customerBlockEmailTemplateId",
                           _appSettings.CurrentValue.CustomerManagementService.CustomerBlockEmailTemplateId)
            .WithParameter("customerBlockSubjectTemplateId",
                           _appSettings.CurrentValue.CustomerManagementService.CustomerBlockSubjectTemplateId)
            .WithParameter("customerUnblockEmailTemplateId",
                           _appSettings.CurrentValue.CustomerManagementService.CustomerUnblockEmailTemplateId)
            .WithParameter("customerUnblockSubjectTemplateId",
                           _appSettings.CurrentValue.CustomerManagementService.CustomerUnblockSubjectTemplateId)
            .WithParameter("customerSupportPhoneNumber",
                           _appSettings.CurrentValue.CustomerManagementService.CustomerSupportPhoneNumber);

            builder.RegisterType <PostProcessService>()
            .As <IPostProcessService>()
            .SingleInstance();

            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .SingleInstance()
            .AutoActivate();

            builder.RegisterType <CustomerWalletCreatedHandler>()
            .As <ICustomerWalletCreatedHandler>()
            .SingleInstance();

            var callRateLimitSettingsDto = new CallRateLimitSettingsDto
            {
                EmailVerificationCallsMonitoredPeriod     = _appSettings.CurrentValue.CustomerManagementService.LimitationSettings.EmailVerificationCallsMonitoredPeriod,
                EmailVerificationMaxAllowedRequestsNumber = _appSettings.CurrentValue.CustomerManagementService.LimitationSettings.EmailVerificationMaxAllowedRequestsNumber,
                PhoneVerificationCallsMonitoredPeriod     = _appSettings.CurrentValue.CustomerManagementService.LimitationSettings.PhoneVerificationCallsMonitoredPeriod,
                PhoneVerificationMaxAllowedRequestsNumber = _appSettings.CurrentValue.CustomerManagementService.LimitationSettings.PhoneVerificationMaxAllowedRequestsNumber,
            };

            builder.RegisterType <CallRateLimiterService>()
            .As <ICallRateLimiterService>()
            .WithParameter(TypedParameter.From(callRateLimitSettingsDto))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.CustomerManagementService.Redis.InstanceName));

            builder.RegisterType <PhoneVerificationService>()
            .As <IPhoneVerificationService>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.CustomerManagementService.PhoneVerificationCodeExpirePeriod))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.CustomerManagementService.PhoneVerificationSmsTemplateId))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.CustomerManagementService.PhoneVerificationCodeLength))
            .SingleInstance();

            builder.RegisterType <EmailRestrictionsService>()
            .As <IEmailRestrictionsService>()
            .WithParameter("allowedEmailDomains", _appSettings.CurrentValue.CustomerManagementService.RegistrationRestrictions.AllowedEmailDomains)
            .WithParameter("allowedEmails", _appSettings.CurrentValue.CustomerManagementService.RegistrationRestrictions.AllowedEmails)
            .SingleInstance();
        }
        public ServiceProvider(ApiPortVSPackage serviceProvider)
        {
            var builder = new ContainerBuilder();

            // VS type registration
            // Registers all of the Visual Studio Package components.
            RegisterVisualStudioComponents(builder, serviceProvider);

            builder.RegisterType <VsBrowserReportViewer>()
            .As <IReportViewer>()
            .SingleInstance();
            builder.RegisterType <ToolbarListReportViewer>()
            .As <IReportViewer>()
            .InstancePerLifetimeScope();
            builder.RegisterType <ApiPortVsAnalyzer>()
            .As <IVsApiPortAnalyzer>()
            .InstancePerLifetimeScope();

            // Service registration
            builder.RegisterInstance(new ProductInformation("ApiPort_VS"))
            .AsSelf();
            builder.RegisterInstance(new AssemblyRedirectResolver(AssemblyDirectory))
            .AsSelf();
            builder.RegisterType <ApiPortService>()
            .As <IApiPortService>()
            .WithParameter(TypedParameter.From <string>(DefaultEndpoint))
            .SingleInstance();
            builder.RegisterType <ApiPortClient>()
            .AsSelf()
            .SingleInstance();
            builder.Register(_ => OptionsModel.Load())
            .As <OptionsModel>()
            .OnRelease(m => m.Save())
            .SingleInstance();
            builder.RegisterType <TargetMapper>()
            .As <ITargetMapper>()
            .OnActivated(h => h.Instance.LoadFromConfig())
            .InstancePerLifetimeScope();
            builder.RegisterType <WindowsFileSystem>()
            .As <IFileSystem>()
            .SingleInstance();

            // Register output services
            builder.RegisterType <ReportGenerator>()
            .As <IReportGenerator>()
            .SingleInstance();
            builder.RegisterType <OutputWindowWriter>()
            .AsSelf()
            .As <IOutputWindowWriter>()
            .As <TextWriter>()
            .SingleInstance();
            builder.RegisterType <TextWriterProgressReporter>()
            .As <IProgressReporter>()
            .SingleInstance();
            builder.RegisterType <ReportFileWriter>()
            .As <IFileWriter>()
            .SingleInstance();

            builder.RegisterInstance(AnalysisOutputToolWindowControl.Model)
            .As <OutputViewModel>()
            .SingleInstance();

            // Register menu handlers
            builder.RegisterType <AnalyzeMenu>()
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <FileListAnalyzer>()
            .AsSelf()
            .InstancePerLifetimeScope();
            builder.RegisterType <ProjectAnalyzer>()
            .AsSelf()
            .InstancePerLifetimeScope();
            builder.RegisterType <COMProjectMapper>()
            .As <IProjectMapper>()
            .SingleInstance();

            // Register option pane services
            builder.RegisterType <OptionsPageControl>()
            .AsSelf()
            .InstancePerLifetimeScope();
            builder.RegisterType <OptionsViewModel>()
            .AsSelf()
            .InstancePerLifetimeScope();

            // Metadata manipulation registrations
            builder.RegisterType <CciDependencyFinder>()
            .As <IDependencyFinder>()
            .InstancePerLifetimeScope();
            builder.RegisterType <CciSourceLineMapper>()
            .As <ISourceLineMapper>()
            .InstancePerLifetimeScope();

            var dte     = Package.GetGlobalService(typeof(DTE)) as DTE;
            var version = new Version(dte.Version);

            if (version.Major == 14)
            {
                builder.RegisterModule(new VS2015.ServiceProvider());
            }
            else
            {
                builder.RegisterModule(new VS2017.ServiceProvider());
            }

            _container = builder.Build();
        }
Beispiel #20
0
        protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration)
        {
            if (_skipRegistration)
            {
                return;
            }

            // Ignore components that provide loggers (and thus avoid a circular dependency below)
            if (registration.Services.OfType <TypedService>().Any(ts => ts.ServiceType == typeof(ILogger) || ts.ServiceType == typeof(LoggerProvider)))
            {
                return;
            }

            PropertyInfo[] targetProperties = null;

            var ra = registration.Activator as ReflectionActivator;

            if (ra != null)
            {
                // As of Autofac v4.7.0 "FindConstructors" will throw "NoConstructorsFoundException" instead of returning an empty array
                // See: https://github.com/autofac/Autofac/pull/895 & https://github.com/autofac/Autofac/issues/733
                ConstructorInfo[] ctors;
                try
                {
                    ctors = ra.ConstructorFinder.FindConstructors(ra.LimitType);
                }
                catch (Exception ex) when(ex.GetType().Name == "NoConstructorsFoundException")  // Avoid needing to upgrade our Autofac reference to 4.7.0
                {
                    ctors = new ConstructorInfo[0];
                }

                var usesLogger =
                    ctors.SelectMany(ctor => ctor.GetParameters()).Any(pi => pi.ParameterType == typeof(ILogger));

                if (_autowireProperties)
                {
                    var logProperties = ra.LimitType
                                        .GetRuntimeProperties()
                                        .Where(c => c.CanWrite && c.PropertyType == typeof(ILogger) && c.SetMethod.IsPublic && !c.SetMethod.IsStatic)
                                        .ToArray();

                    if (logProperties.Any())
                    {
                        targetProperties = logProperties;
                        usesLogger       = true;
                    }
                }

                // Ignore components known to be without logger dependencies
                if (!usesLogger)
                {
                    return;
                }
            }

            registration.Preparing += (sender, args) =>
            {
                var log = args.Context.Resolve <ILogger>().ForContext(registration.Activator.LimitType);
                args.Parameters = new[] { TypedParameter.From(log) }.Concat(args.Parameters);
            };

            if (targetProperties != null)
            {
                registration.Activating += (sender, args) =>
                {
                    var log = args.Context.Resolve <ILogger>().ForContext(registration.Activator.LimitType);
                    foreach (var targetProperty in targetProperties)
                    {
                        targetProperty.SetValue(args.Instance, log);
                    }
                };
            }
        }
Beispiel #21
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <HealthService>()
            .As <IHealthService>()
            .SingleInstance();

            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.ConstraintsGroups))
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .SingleInstance();

            builder.RegisterType <RiskConstrainsInitializer>()
            .AsSelf()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.ConstraintsGroups));

            builder.RegisterType <OperationValidationRepository>()
            .As <IOperationValidationRepository>()
            .WithParameter(TypedParameter.From(_settings.ConnectionString(x => x.Db.AzureDataConnString)))
            .SingleInstance();

            builder.RegisterType <StatisticsRepository>()
            .As <IStatisticsRepository>()
            .AsSelf()
            .WithParameter(TypedParameter.From(_settings.CurrentValue.Db.MongoDataConnString))
            .SingleInstance();

            builder.RegisterType <OperationValidationService>()
            .As <IOperationValidationService>()
            .SingleInstance();

            builder.RegisterType <StatisticsService>()
            .As <IStatisticsService>()
            .SingleInstance();

            builder.RegisterType <OperationRiskEstimator>()
            .As <IOperationRiskEstimator>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsRegistry>()
            .As <IRiskConstraintsRegistry>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsRegistryConfigurator>()
            .As <IRiskConstraintsRegistryConfigurator>()
            .SingleInstance();

            builder.RegisterType <RiskConstraintsFactory>()
            .As <IRiskConstraintsFactory>()
            .SingleInstance();

            builder.RegisterType <BlockchainRiskControlServiceImpl>()
            .AsSelf()
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    BlockchainRiskControlService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        BlockchainRiskControlService.BindService(ctx.Resolve <BlockchainRiskControlServiceImpl>()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", 5005, ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.RegisterInstance(
                new TelegramBotClient(string.IsNullOrEmpty(_settings.CurrentValue.Telegram?.Token) ? "1234:test" : _settings.CurrentValue.Telegram?.Token)
                ).As <ITelegramBotClient>().SingleInstance();
        }
Beispiel #22
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <StartupManager>()
            .As <IStartupManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .AutoActivate()
            .SingleInstance();

            builder.RegisterType <Link4PayServiceImpl>()
            .AsSelf()
            .WithParameter("supportedCountries", _appSettings.CurrentValue.Link4PayService.SupportedCountries)
            .WithParameter("supportedCurrencies", _appSettings.CurrentValue.Link4PayService.SupportedCurrencies)
            .SingleInstance();

            builder.Register(ctx =>
            {
                var reflectionServiceImpl = new ReflectionServiceImpl(
                    Link4PayService.Descriptor
                    );
                return(new Server
                {
                    Services =
                    {
                        Link4PayService.BindService(ctx.Resolve <Link4PayServiceImpl>()),
                        ServerReflection.BindService(reflectionServiceImpl)
                    },
                    Ports =
                    {
                        new ServerPort("0.0.0.0", _appSettings.CurrentValue.Link4PayService.GrpcPort,
                                       ServerCredentials.Insecure)
                    }
                });
            }
                             ).SingleInstance();

            builder.RegisterInstance(
                new KeyVaultClient(
                    async(string authority, string resource, string scope) =>
            {
                var authContext = new AuthenticationContext(authority);
                var clientCred  =
                    new ClientCredential(_appSettings.CurrentValue.Link4PayService.KeyVault.ClientId, _appSettings.CurrentValue.Link4PayService.KeyVault.ClientSecret);
                var result = await authContext.AcquireTokenAsync(resource, clientCred);
                if (result == null)
                {
                    throw new InvalidOperationException("Failed to retrieve access token for Key Vault");
                }

                return(result.AccessToken);
            }
                    ));

            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.Link4Pay);
            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.KeyVault);

            builder.RegisterType <EncryptionService>()
            .As <IEncryptionService>()
            .SingleInstance();

            builder.RegisterType <Link4PayApiService>()
            .As <ILink4PayApiService>()
            .SingleInstance();

            builder.RegisterType <AntiFraudChecker>()
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Link4PayService.AntiFraudCheckPaymentPeriod))
            .WithParameter(TypedParameter.From(_appSettings.CurrentValue.Link4PayService.AntiFraudCheckRegistrationDateSince))
            .WithParameter("notificationEmail", _appSettings.CurrentValue.Link4PayService.AntiFraudNotificationEmail)
            .WithParameter("chatId", _appSettings.CurrentValue.Link4PayService.Telegram.ChatId);

            builder.RegisterType <PaymentOkEmailSender>()
            .As <IPaymentNotifier>()
            .SingleInstance();

            builder.RegisterInstance(_appSettings.CurrentValue.Link4PayService.Telegram);

            builder.RegisterInstance(
                string.IsNullOrEmpty(_appSettings.CurrentValue.Link4PayService.Telegram.Token)
                ? new Mock <ITelegramBotClient>().Object
                : new TelegramBotClient(_appSettings.CurrentValue.Link4PayService.Telegram.Token)
                ).As <ITelegramBotClient>().SingleInstance();
        }
Beispiel #23
0
        protected override void Load(ContainerBuilder builder)
        {
            var encryptionKey = Environment.GetEnvironmentVariable("EncryptionKey");
            var encryptionIv  = Environment.GetEnvironmentVariable("EncryptionIV");

            builder.RegisterInstance(new AesSerializer(encryptionKey, encryptionIv))
            .As <IAesSerializer>()
            .SingleInstance();

            builder.RegisterType <EncryptionService>()
            .As <IEncryptionService>()
            .SingleInstance();

            builder.RegisterType <AdminProfileService>()
            .As <IAdminProfileService>()
            .SingleInstance();

            builder.RegisterType <CustomerProfileService>()
            .As <ICustomerProfileService>()
            .SingleInstance();

            builder.RegisterType <PartnerContactService>()
            .As <IPartnerContactService>()
            .SingleInstance();

            builder.RegisterType <ReferralHotelProfileService>()
            .As <IReferralHotelProfileService>()
            .SingleInstance();

            builder.RegisterType <ReferralLeadProfileService>()
            .As <IReferralLeadProfileService>()
            .SingleInstance();

            builder.RegisterType <ReferralFriendProfileService>()
            .As <IReferralFriendProfileService>()
            .SingleInstance();

            builder.RegisterType <StatisticsService>()
            .As <IStatisticsService>()
            .SingleInstance();

            builder.RegisterType <PaymentProviderDetailsService>()
            .As <IPaymentProviderDetailsService>()
            .SingleInstance();

            var apiKeysPairs = Environment.GetEnvironmentVariable("CPApiKeysPairs");

            builder.RegisterType <ApiKeyService>()
            .As <IApiKeyService>()
            .SingleInstance()
            .WithParameter(TypedParameter.From(apiKeysPairs));

            builder.RegisterType <StartupManager>()
            .WithParameter("encryptionKey", encryptionKey)
            .WithParameter("encryptionIv", encryptionIv)
            .As <IStartupManager>()
            .SingleInstance();

            builder.RegisterType <ShutdownManager>()
            .As <IShutdownManager>()
            .SingleInstance()
            .AutoActivate();
        }
Beispiel #24
0
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterModule(new FiberModule <DialogTask>());

            // singleton components

            builder
            .Register(c => new ResourceManager("Microsoft.Bot.Builder.Resource.Resources", typeof(Resource.Resources).Assembly))
            .As <ResourceManager>()
            .SingleInstance();

            // every lifetime scope is driven by a message

            builder
            .Register((c, p) => p.TypedAs <IMessageActivity>())
            .AsSelf()
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // make the address and cookie available for the lifetime scope

            builder
            .Register(c => Address.FromActivity(c.Resolve <IActivity>()))
            .AsImplementedInterfaces()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            builder
            .RegisterType <ResumptionCookie>()
            .AsSelf()
            .InstancePerMatchingLifetimeScope(LifetimeScopeTag);

            // components not marked as [Serializable]
            builder
            .RegisterType <MicrosoftAppCredentials>()
            .AsSelf()
            .SingleInstance();

            builder
            // not resolving IEqualityComparer<IAddress> from container because it's a very local policy
            // and yet too broad of an interface.  could explore using tags for registration overrides.
            .Register(c => new LocalMutualExclusion <IAddress>(new ConversationAddressComparer()))
            .As <IScope <IAddress> >()
            .SingleInstance();

            builder
            .Register(c => new ConnectorClientFactory(c.Resolve <IAddress>(), c.Resolve <MicrosoftAppCredentials>()))
            .As <IConnectorClientFactory>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeConnectorClient())
            .As <IConnectorClient>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IConnectorClientFactory>().MakeStateClient())
            .As <IStateClient>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new DetectChannelCapability(c.Resolve <IAddress>()))
            .As <IDetectChannelCapability>()
            .InstancePerLifetimeScope();

            builder
            .Register(c => c.Resolve <IDetectChannelCapability>().Detect())
            .As <IChannelCapability>()
            .InstancePerLifetimeScope();

            builder.RegisterType <ConnectorStore>()
            .AsSelf()
            .InstancePerLifetimeScope();

            // If bot wants to use InMemoryDataStore instead of
            // ConnectorStore, the below registration should be used
            // as the inner IBotDataStore for CachingBotDataStore

            /*builder.RegisterType<InMemoryDataStore>()
             *  .AsSelf()
             *  .SingleInstance(); */

            builder.Register(c => new CachingBotDataStore(c.Resolve <ConnectorStore>(),
                                                          CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency))
            .As <IBotDataStore <BotData> >()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <JObjectBotData>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new DialogTaskManagerBotDataLoader(c.Resolve <JObjectBotData>(),
                                                              c.Resolve <IDialogTaskManager>()))
            .As <IBotData>()
            .InstancePerLifetimeScope();

            builder
            .Register((c, p) => new BotDataBagStream(p.TypedAs <IBotDataBag>(), p.TypedAs <string>()))
            .As <Stream>()
            .InstancePerDependency();

            builder.Register(c => new DialogTaskManager(DialogModule.BlobKey,
                                                        c.Resolve <JObjectBotData>(),
                                                        c.Resolve <IStackStoreFactory <DialogTask> >(),
                                                        c.Resolve <Func <IDialogStack, CancellationToken, IDialogContext> >()))
            .AsSelf()
            .As <IDialogTaskManager>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DialogContext>()
            .As <IDialogContext>()
            .InstancePerDependency();


            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();

                Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > make = (taskId, botDataBag) =>
                {
                    var stream = cc.Resolve <Stream>(TypedParameter.From(botDataBag), TypedParameter.From(taskId));
                    return(cc.Resolve <IStore <IFiberLoop <DialogTask> > >(TypedParameter.From(stream)));
                };

                return(make);
            })
            .As <Func <string, IBotDataBag, IStore <IFiberLoop <DialogTask> > > >()
            .InstancePerDependency();


            builder.Register(c => c.Resolve <IDialogTaskManager>().DialogTasks[0])
            .As <IDialogStack>()
            .As <IDialogTask>()
            .InstancePerLifetimeScope();


            // Scorable implementing "/deleteprofile"
            builder
            .Register(c => new Regex("^(\\s)*/deleteprofile", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
            .Keyed <Regex>(Key_DeleteProfile_Regex)
            .SingleInstance();

            builder
            .Register(c => new DeleteProfileScorable(c.Resolve <IDialogStack>(), c.Resolve <IBotData>(), c.Resolve <IBotToUser>(), c.ResolveKeyed <Regex>(Key_DeleteProfile_Regex)))
            .As <IScorable <IActivity, double> >()
            .InstancePerLifetimeScope();

            builder
            .Register(c =>
            {
                var stack      = c.Resolve <IDialogStack>();
                var fromStack  = stack.Frames.Select(f => f.Target).OfType <IScorable <IActivity, double> >();
                var fromGlobal = c.Resolve <IScorable <IActivity, double>[]>();
                // since the stack of scorables changes over time, this should be lazy
                var lazyScorables = fromStack.Concat(fromGlobal);
                var scorable      = new TraitsScorable <IActivity, double>(c.Resolve <ITraits <double> >(), c.Resolve <IComparer <double> >(), lazyScorables);
                return(scorable);
            })
            .InstancePerLifetimeScope()
            .AsSelf();

            builder
            .RegisterType <NullActivityLogger>()
            .AsImplementedInterfaces()
            .SingleInstance();

            builder
            .Register(c =>
            {
                var cc = c.Resolve <IComponentContext>();
                Func <IPostToBot> makeInner = () =>
                {
                    IPostToBot post = new ReactiveDialogTask(cc.Resolve <IDialogTask>(), cc.Resolve <Func <IDialog <object> > >());
                    post            = new ExceptionTranslationDialogTask(post);
                    post            = new LocalizedDialogTask(post);
                    post            = new ScoringDialogTask <double>(post, cc.Resolve <TraitsScorable <IActivity, double> >());
                    return(post);
                };

                IPostToBot outer = new PersistentDialogTask(makeInner, cc.Resolve <IBotData>());
                outer            = new SerializingDialogTask(outer, cc.Resolve <IAddress>(), c.Resolve <IScope <IAddress> >());
                outer            = new PostUnhandledExceptionToUserTask(outer, cc.Resolve <IBotToUser>(), cc.Resolve <ResourceManager>(), cc.Resolve <TraceListener>());
                outer            = new LogPostToBot(outer, cc.Resolve <IActivityLogger>());
                return(outer);
            })
            .As <IPostToBot>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <AlwaysSendDirect_BotToUser>()
            .AsSelf()
            .InstancePerLifetimeScope();

            builder
            .Register(c => new LogBotToUser(new MapToChannelData_BotToUser(
                                                c.Resolve <AlwaysSendDirect_BotToUser>(),
                                                new List <IMessageActivityMapper> {
                new KeyboardCardMapper()
            }), c.Resolve <IActivityLogger>()))
            .As <IBotToUser>()
            .InstancePerLifetimeScope();
        }
        public static TId GetScopeId <TMessage, TId>(this ILifetimeScopeRegistry <TId> registry, ConsumeContext <TMessage> context)
            where TMessage : class
        {
            var scopeId = default(TId);

            // first, try to use the message-based scopeId provider
            if (registry.TryResolve(out ILifetimeScopeIdAccessor <TMessage, TId> provider) && provider.TryGetScopeId(context.Message, out scopeId))
            {
                return(scopeId);
            }

            // second, try to use the consume context based message version
            var idProvider =
                registry.ResolveOptional <ILifetimeScopeIdProvider <TId> >(TypedParameter.From(context), TypedParameter.From <ConsumeContext>(context));

            if (idProvider != null && idProvider.TryGetScopeId(out scopeId))
            {
                return(scopeId);
            }

            // okay, give up, default it is
            return(scopeId);
        }
Beispiel #26
0
        public static async Task <ServiceProvider> CreateAsync(ApiPortVSPackage serviceProvider)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <VsBrowserReportViewer>()
            .As <IReportViewer>()
            .SingleInstance();
            builder.RegisterType <ToolbarListReportViewer>()
            .As <IReportViewer>()
            .InstancePerLifetimeScope();
            builder.RegisterType <ApiPortVsAnalyzer>()
            .As <IVsApiPortAnalyzer>()
            .InstancePerLifetimeScope();

            // Service registration
            builder.RegisterInstance(new ProductInformation("ApiPort_VS"))
            .AsSelf();
            builder.RegisterInstance(new AssemblyRedirectResolver(AssemblyDirectory))
            .AsSelf();
            builder.RegisterType <VisualStudioProxyProvider>()
            .As <IProxyProvider>()
            .SingleInstance();
            builder.RegisterType <ApiPortService>()
            .As <IApiPortService>()
            .WithParameter(TypedParameter.From(DefaultEndpoint))
            .SingleInstance();
            builder.RegisterType <ApiPortClient>()
            .AsSelf()
            .SingleInstance();
            builder.Register(_ => OptionsModel.Load())
            .As <OptionsModel>()
            .OnRelease(m => m.Save())
            .SingleInstance();
            builder.RegisterType <TargetMapper>()
            .As <ITargetMapper>()
            .OnActivated(h => h.Instance.LoadFromConfig())
            .InstancePerLifetimeScope();
            builder.RegisterType <WindowsFileSystem>()
            .As <IFileSystem>()
            .SingleInstance();

            // Register output services
            builder.RegisterType <ReportGenerator>()
            .As <IReportGenerator>()
            .SingleInstance();
            builder.RegisterType <OutputWindowWriter>()
            .AsSelf()
            .As <IOutputWindowWriter>()
            .As <TextWriter>()
            .SingleInstance();
            builder.RegisterType <StatusBarProgressReporter>()
            .As <IProgressReporter>()
            .SingleInstance();
            builder.RegisterType <ReportFileWriter>()
            .As <IFileWriter>()
            .SingleInstance();

            builder.Register(GetOutputViewModel)
            .As <OutputViewModel>()
            .SingleInstance();

            // Register menu handlers
            builder.RegisterType <AnalyzeMenu>()
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <FileListAnalyzer>()
            .AsSelf()
            .InstancePerLifetimeScope();
            builder.RegisterType <ProjectAnalyzer>()
            .AsSelf()
            .InstancePerLifetimeScope();

            // Register option pane services
            builder.RegisterType <OptionsPageControl>()
            .AsSelf()
            .InstancePerLifetimeScope();
            builder.RegisterType <OptionsViewModel>()
            .AsSelf()
            .InstancePerLifetimeScope();

            // Metadata manipulation registrations
            builder.RegisterType <CciDependencyFinder>()
            .As <IDependencyFinder>()
            .InstancePerLifetimeScope();
            builder.RegisterType <CciSourceLineMapper>()
            .As <ISourceLineMapper>()
            .InstancePerLifetimeScope();

            // VS type registration
            // Registers all of the Visual Studio Package components.
            await RegisterVisualStudioComponentsAsync(builder, serviceProvider);

            return(new ServiceProvider(builder.Build()));
        }
Beispiel #27
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType <AssetsService>()
            .WithParameter(TypedParameter.From(_config.Cache.AssetsCacheDuration))
            .As <IAssetsService>()
            .As <IStartable>()
            .AutoActivate();

            builder.RegisterType <OrderbooksService>()
            .As <IOrderbooksService>()
            .WithParameter(TypedParameter.From(_config.Redis.OrderBooksCacheKeyPattern))
            .SingleInstance();

            var cache = new RedisCache(new RedisCacheOptions
            {
                Configuration = _config.Redis.RedisConfiguration,
                InstanceName  = _config.Redis.InstanceName
            });

            builder.RegisterInstance(cache)
            .As <IDistributedCache>()
            .SingleInstance();

            builder.RegisterMarketDataClient(new MarketDataServiceClientSettings {
                GrpcServiceUrl = _config.Services.MarketDataGrpcServiceUrl
            });

            builder.Register(ctx =>
            {
                var logger = ctx.Resolve <ILoggerFactory>();
                return(logger.ToLykke());
            }).As <ILogFactory>();

            builder.RegisterMeClient(_config.MatchingEngine.GetIpEndPoint());

            builder.RegisterType <KeyUpdateSubscriber>()
            .As <IStartable>()
            .AutoActivate()
            .WithParameter("connectionString", _config.RabbitMq.HftInternal.ConnectionString)
            .WithParameter("exchangeName", _config.RabbitMq.HftInternal.ExchangeName)
            .SingleInstance();

            builder.RegisterHftInternalClient(_config.Services.HftInternalServiceUrl);

            builder.RegisterType <TokenService>()
            .As <ITokenService>()
            .SingleInstance();

            builder.RegisterType <BalanceService>()
            .As <IBalanceService>()
            .SingleInstance();

            builder.RegisterType <ValidationService>()
            .AsSelf()
            .SingleInstance();

            builder.RegisterType <IdempotencyService>()
            .AsSelf()
            .SingleInstance();

            var reconnectTimeoutInSec = Environment.GetEnvironmentVariable("NOSQL_PING_INTERVAL") ?? "15";

            builder.Register(ctx =>
            {
                var client = new MyNoSqlTcpClient(() => _config.MyNoSqlServer.ReaderServiceUrl, $"{ApplicationInformation.AppName}-{Environment.MachineName}", int.Parse(reconnectTimeoutInSec));
                client.Start();
                return(client);
            }).AsSelf().SingleInstance();

            builder.RegisterInstance(_config.FeeSettings)
            .AsSelf();

            builder.Register(ctx =>
                             new MyNoSqlReadRepository <TickerEntity>(ctx.Resolve <MyNoSqlTcpClient>(), _config.MyNoSqlServer.TickersTableName)
                             ).As <IMyNoSqlServerDataReader <TickerEntity> >().SingleInstance();

            builder.Register(ctx =>
                             new MyNoSqlReadRepository <PriceEntity>(ctx.Resolve <MyNoSqlTcpClient>(), _config.MyNoSqlServer.PricesTableName)
                             ).As <IMyNoSqlServerDataReader <PriceEntity> >().SingleInstance();

            builder.Register(ctx =>
                             new MyNoSqlReadRepository <OrderbookEntity>(ctx.Resolve <MyNoSqlTcpClient>(), _config.MyNoSqlServer.OrderbooksTableName)
                             ).As <IMyNoSqlServerDataReader <OrderbookEntity> >().SingleInstance();

            builder.Register(ctx =>
                             new MyNoSqlReadRepository <BalanceEntity>(ctx.Resolve <MyNoSqlTcpClient>(), _config.MyNoSqlServer.BalancesTableName)
                             ).As <IMyNoSqlServerDataReader <BalanceEntity> >().SingleInstance();

            builder.RegisterType <PricesStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <TickersStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <OrderbookStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <BalancesStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <OrdersStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <TradesStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <PublicTradesStreamService>()
            .WithParameter(TypedParameter.From(true))
            .AsSelf()
            .SingleInstance();
            builder.RegisterType <StreamsManager>().AsSelf().SingleInstance();
            builder.RegisterType <SiriusWalletsService>()
            .As <ISiriusWalletsService>()
            .WithParameter(TypedParameter.From(_config.Services.SiriusApiServiceClient.BrokerAccountId))
            .WithParameter(TypedParameter.From(_config.Services.SiriusApiServiceClient.WalletsActiveRetryCount))
            .WithParameter(TypedParameter.From(_config.Services.SiriusApiServiceClient.WaitForActiveWalletsTimeout))
            .SingleInstance();

            builder.RegisterType <TradesSubscriber>()
            .As <IStartable>()
            .AutoActivate()
            .WithParameter("connectionString", _config.RabbitMq.Orders.ConnectionString)
            .WithParameter("exchangeName", _config.RabbitMq.Orders.ExchangeName)
            .SingleInstance();

            builder.Register(ctx =>
                             new TradesAdapterClient(_config.Services.TradesAdapterServiceUrl,
                                                     ctx.Resolve <ILogFactory>().CreateLog(nameof(TradesAdapterClient)))
                             )
            .As <ITradesAdapterClient>()
            .SingleInstance();

#pragma warning disable 618
            builder.Register(x => new KycStatusServiceClient(_config.Services.KycServiceClient, x.Resolve <ILogFactory>()))
#pragma warning restore 618
            .As <IKycStatusService>()
            .SingleInstance();

            builder.RegisterClientAccountClient(_config.Services.ClientAccountServiceUrl);

            builder.RegisterOperationsClient(_config.Services.OperationsServiceUrl);

            builder.RegisterClientDialogsClient(_config.Services.ClientDialogsServiceUrl);

            builder.RegisterInstance(
                new Swisschain.Sirius.Api.ApiClient.ApiClient(_config.Services.SiriusApiServiceClient.GrpcServiceUrl, _config.Services.SiriusApiServiceClient.ApiKey)
                ).As <Swisschain.Sirius.Api.ApiClient.IApiClient>();

            builder.RegisterType <PublicTradesSubscriber>()
            .As <IStartable>()
            .AutoActivate()
            .WithParameter("connectionString", _config.RabbitMq.PublicTrades.ConnectionString)
            .WithParameter("exchangeName", _config.RabbitMq.PublicTrades.ExchangeName)
            .SingleInstance();


            builder.Register(ctx =>
                             AzureTableStorage <IdempotentEntity> .Create(ConstantReloadingManager.From(_config.Db.DataConnString),
                                                                          "HftApiIdempotency", ctx.Resolve <ILogFactory>())
                             ).As <INoSQLTableStorage <IdempotentEntity> >().SingleInstance();
        }
Beispiel #28
0
        public async Task InMemoryBotDataStoreTest()
        {
            var chain = Chain.PostToChain().Select(m => m.Text).ContinueWith <string, string>(async(context, result) =>
            {
                int t = 0;
                context.UserData.TryGetValue("count", out t);
                if (t > 0)
                {
                    int value;
                    Assert.IsTrue(context.ConversationData.TryGetValue("conversation", out value));
                    Assert.AreEqual(t - 1, value);
                    Assert.IsTrue(context.UserData.TryGetValue("user", out value));
                    Assert.AreEqual(t + 1, value);
                    Assert.IsTrue(context.PrivateConversationData.TryGetValue("PrivateConversationData", out value));
                    Assert.AreEqual(t + 2, value);
                }

                context.ConversationData.SetValue("conversation", t);
                context.UserData.SetValue("user", t + 2);
                context.PrivateConversationData.SetValue("PrivateConversationData", t + 3);
                context.UserData.SetValue("count", ++t);
                return(Chain.Return($"{t}:{await result}"));
            }).PostToUser();
            Func <IDialog <object> > MakeRoot = () => chain;

            using (new FiberTestBase.ResolveMoqAssembly(chain))
                using (var container = Build(Options.InMemoryBotDataStore, new MockConnectorFactory(new BotIdResolver("testBot")), chain))
                {
                    var msg = DialogTestBase.MakeTestMessage();
                    msg.Text = "test";
                    using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                    {
                        scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));

                        await Conversation.SendAsync(scope, msg);

                        var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();
                        Assert.AreEqual("1:test", reply.Text);
                        var store = scope.Resolve <CachingBotDataStore_LastWriteWins>();
                        Assert.AreEqual(0, store.cache.Count);
                        var dataStore = scope.Resolve <InMemoryDataStore>();
                        Assert.AreEqual(3, dataStore.store.Count);
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        using (var scope = DialogModule.BeginLifetimeScope(container, msg))
                        {
                            scope.Resolve <Func <IDialog <object> > >(TypedParameter.From(MakeRoot));
                            await Conversation.SendAsync(scope, msg);

                            var reply = scope.Resolve <Queue <IMessageActivity> >().Dequeue();
                            Assert.AreEqual($"{i+2}:test", reply.Text);
                            var store = scope.Resolve <CachingBotDataStore_LastWriteWins>();
                            Assert.AreEqual(0, store.cache.Count);
                            var dataStore = scope.Resolve <InMemoryDataStore>();
                            Assert.AreEqual(3, dataStore.store.Count);
                            string val = string.Empty;
                            Assert.IsTrue(scope.Resolve <IBotData>().PrivateConversationData.TryGetValue(DialogModule.BlobKey, out val));
                            Assert.AreNotEqual(string.Empty, val);
                        }
                    }
                }
        }
Beispiel #29
0
 public ChangeLogPipeline Build()
 {
     return(Container.Resolve <ChangeLogPipeline>(
                TypedParameter.From <IEnumerable <IChangeLogTask> >(m_Tasks)
                ));
 }
        public void Test_Core_Create_CtorIAnimalParam()
        {
            var fact = AutoFactory.Factory.Create <Animal>(new[] { typeof(Animal).GetTypeInfo().Assembly }, TypedParameter.From <IAnimal>(new Cat(2)));
            var dog  = fact.SeekPart(p => p.Name == "Dog");

            Assert.AreEqual(1, Animal.Dogs);
            Assert.AreEqual(2, dog.Friend.Age);
            Assert.AreEqual("Cat", dog.Friend.GetType().Name);
            Assert.AreEqual(1, Animal.CtorIAnimal);
        }