public static void AddMvc(
            this ServiceCollectionWrapper serviceCollectionWrapper,
            MvcOptions mvcOptions = null,
            Action <IAddMvcBuilder> configureAddMvcBuilder = null)
        {
            var serv = serviceCollectionWrapper.Services;

            //First step. Register all services, that can be registered before IAddMvcBuilder configurations.
            AddServises_NotRequiredBuilder(serviceCollectionWrapper);

            //Second step. Init AddMvcBuilder parameters with MvcOptions to pass it to callback.
            mvcOptions = mvcOptions ?? new MvcOptions();
            var addMvcBuilder = InitAddMvcBuilder(serviceCollectionWrapper, mvcOptions);

            //Third step. Register all services based on IAddMvcBuilder.
            AddServises_RequiredBuilder(
                serviceCollectionWrapper,
                addMvcBuilder
                );

            //!Add controllers services.
            ControllersMiddlewareExtensions.AddControllersServices(addMvcBuilder);

            //Custom configs.
            configureAddMvcBuilder?.Invoke(addMvcBuilder);

            //Finish. Register builders to be resolved in middleware.
            serv.AddSingleton <IAddMvcBuilder>(addMvcBuilder);
        }
Ejemplo n.º 2
0
        public static FrameworkConfigurator UseServiceCollection(
            this FrameworkConfigurator configurator,
            IServiceCollection services)
        {
            var wrapper = new ServiceCollectionWrapper(services);

            return(configurator.SetDependencyFramework(wrapper));
        }
        static void AddServises_RequiredBuilder(ServiceCollectionWrapper serviceCollectionWrapper, IAddMvcBuilder addMvcBuilder)
        {
            var serv = serviceCollectionWrapper.Services;

            foreach (var controllerType in addMvcBuilder.Controllers)
            {
                serv.AddTransient(controllerType);
            }
        }
Ejemplo n.º 4
0
            public async Task OnStartedServiceAsync(OperationContext context, ICacheServerServices cacheServices)
            {
                CacheServiceStartup.UseExternalServices(WebHostBuilder, context, HostParameters);

                WebHostBuilder.ConfigureServices(services =>
                {
                    services.AddSingleton <DistributedCacheServiceConfiguration>(ServiceConfiguration);

                    if (ServiceConfiguration.ContentCache != null)
                    {
                        if (cacheServices.PushFileHandler != null && cacheServices.StreamStore != null)
                        {
                            services.AddSingleton <ContentCacheService>(sp =>
                            {
                                return(new ContentCacheService(
                                           ServiceConfiguration.ContentCache,
                                           cacheServices.PushFileHandler,
                                           cacheServices.StreamStore));
                            });
                        }
                    }

                    if (UseGrpc)
                    {
                        services.AddSingleton(cacheServices);

                        var grpcServiceCollection = new ServiceCollectionWrapper(services);

                        foreach (var grpcEndpoint in cacheServices.GrpcEndpoints)
                        {
                            grpcEndpoint.AddServices(grpcServiceCollection);
                        }

                        services.AddSingleton <BinderConfiguration>(MetadataServiceSerializer.BinderConfiguration);
                        services.AddCodeFirstGrpc();
                    }
                });

                WebHost = WebHostBuilder.Build();

                // Get and start the DeploymentProxyService
                ProxyService        = WebHost.Services.GetService <DeploymentProxyService>();
                ContentCacheService = WebHost.Services.GetService <ContentCacheService>();

                if (ProxyService != null)
                {
                    await ProxyService.StartupAsync(context).ThrowIfFailureAsync();
                }

                if (ContentCacheService != null)
                {
                    await ContentCacheService.StartupAsync(context).ThrowIfFailureAsync();
                }

                await WebHost.StartAsync(context.Token);
            }
Ejemplo n.º 5
0
 public static void AddSessionStorage(this ServiceCollectionWrapper @this, Func <IServiceProvider, ISessionStorageProvider> func)
 {
     if (func == null)
     {
         throw new ArgumentNullException(nameof(func));
     }
     @this.Services.AddSingleton <ISessionStorageProvider>(
         func
         );
 }
        static IAddMvcBuilder InitAddMvcBuilder(ServiceCollectionWrapper serviceCollectionWrapper, MvcOptions mvcOptions)
        {
            var            serv          = serviceCollectionWrapper.Services;
            IAddMvcBuilder addMvcBuilder = new AddMvcBuilder(
                mvcOptions,
                serv
                );

            ControllersMiddlewareExtensions.InitAddMvcBuilder(mvcOptions, addMvcBuilder);
            return(addMvcBuilder);
        }
 /// <summary>
 /// Here only musthave middleware services.
 /// </summary>
 void AddMandatoryServices(ServiceCollectionWrapper serviceCollectionWrapper)
 {
     serviceCollectionWrapper.AddPendingExceededChecker(
         (serviceProvider) => new CreationTimePendingExceededChecker(TimeSpan.FromMinutes(30))
         );
     serviceCollectionWrapper.AddExecutionManager <ThreadPoolExecutionManager>();
     serviceCollectionWrapper.AddBotExt();
     serviceCollectionWrapper.Services.AddLogging();
     serviceCollectionWrapper.AddExceptionHandling();
     serviceCollectionWrapper.LoggingAdvancedConfigure(new LoggingAdvancedOptions());
     serviceCollectionWrapper.AddRamSessionStorage();
 }
 /// <summary>
 /// If you want to use same <see cref="IServiceProvider"/> in ASP.NET and <see cref="Telegram.Bot.AspNetPipeline"/>
 /// you can user ServiceProviderBuilderDelegate. Pass here ASP.NET IServiceCollection (to register there default and yours
 /// services) and pass builded <see cref="IServiceProvider"/> to <see cref="BotManager.Setup"/>.
 /// <para></para>
 /// If you will use same <see cref="IServiceCollection"/> for two or more <see cref="BotManager"/>s it probably will broke
 /// half of middleware.
 /// </summary>
 public BotManager(
     ITelegramBotClient bot,
     IServiceCollection servicesCollection = null
     )
 {
     if (bot == null)
     {
         throw new ArgumentNullException(nameof(bot));
     }
     _bot = bot;
     servicesCollection        = servicesCollection ?? new ServiceCollection();
     _serviceCollectionWrapper = new ServiceCollectionWrapper(servicesCollection);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Init default <see cref="RamSessionStorageProvider"/>. Used by default.
        /// </summary>
        /// <param name="this"></param>
        /// <param name="sessionTimeout">Default is 30 minutes.</param>
        /// <param name="checkInterval">Default is 5 minutes.</param>
        public static void AddRamSessionStorage(
            this ServiceCollectionWrapper @this,
            TimeSpan?sessionTimeout = null,
            TimeSpan?checkInterval  = null
            )
        {
            var sessionStorage = new RamSessionStorageProvider(sessionTimeout, checkInterval);

            @this.Services.AddSingleton <ISessionStorageProvider>(
                sessionStorage
                );
            @this.Services.AddSingleton <RamSessionStorageProvider>(
                sessionStorage
                );
            @this.RegisterForDispose <RamSessionStorageProvider>();
        }
Ejemplo n.º 10
0
 public static void InitLogger(ServiceCollectionWrapper servicesWrap)
 {
     servicesWrap.LoggingAdvancedConfigure(new LoggingAdvancedOptions
     {
         //LoggingWithSerialization = true
     });
     //Default way with Services.AddLogging doesn't work for me.
     servicesWrap.Services.AddSingleton <ILoggerFactory>(new LoggerFactory(new ILoggerProvider[]
     {
         new NLogLoggerProvider(
             new NLogProviderOptions()
         {
             IncludeScopes            = true,
             CaptureMessageProperties = true
         })
     }));
 }
        static void AddServises_NotRequiredBuilder(ServiceCollectionWrapper serviceCollectionWrapper)
        {
            var serv = serviceCollectionWrapper.Services;

            var globalSearchBagProvider = new GlobalSearchBagProvider();

            serv.AddSingleton <IGlobalSearchBagProvider>(globalSearchBagProvider);
            serv.AddSingleton <GlobalSearchBagProvider>(globalSearchBagProvider);

            serv.AddSingleton <IContextPreparer, ContextPreparer>();

            //Register services bus for services, created in MvcMiddleware.
            var servicesBus = new ServicesBus();

            serv.AddSingleton <ServicesBus>(servicesBus);
            serv.AddSingleton <IMainRouterProvider>(servicesBus);
            serv.AddSingleton <IOuterMiddlewaresInformerProvider>(servicesBus);
            serv.AddSingleton <IMvcFeaturesProvider>(servicesBus);
            //Controllers service.
            serv.AddSingleton <IMainModelBinderProvider>(servicesBus);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Note: Current middleware is registered automatically.
 /// </summary>
 internal static void AddBotExt(this ServiceCollectionWrapper @this)
 {
     @this.Services.AddSingleton <ImprovedBotMiddleware>();
     @this.Services.AddSingleton <IUpdateContextSearchBag, UpdateContextSearchBag>();
     @this.Services.AddSingleton <IBotExtSingleton, BotExtSingleton>();
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Mandatory used in <see cref="BotManager"/>.
 /// </summary>
 internal static void AddExceptionHandling(this ServiceCollectionWrapper @this)
 {
     @this.Services.AddSingleton <ExceptionHandlingMiddleware>();
 }
        /// <summary>
        /// Here you can edit logging settings specialized for current library.
        /// </summary>
        public static void LoggingAdvancedConfigure(this ServiceCollectionWrapper @this, LoggingAdvancedOptions options)
        {
            Func <LoggingAdvancedOptions> func = () => options;

            @this.Services.AddSingleton(func);
        }
Ejemplo n.º 15
0
 public static void AddSessionStorage <TSessionStorageProvider>(this ServiceCollectionWrapper @this)
     where TSessionStorageProvider : class, ISessionStorageProvider
 {
     @this.Services.AddSingleton <ISessionStorageProvider, TSessionStorageProvider>();
 }
        /// <summary>
        /// Execute initialization callbacks and build pipeline.
        /// <para></para>
        /// Called automatically on Start() first call.
        /// </summary>
        /// <param name="serviceProvider">
        /// If not null - will use passed provider instead builded from service collection.
        /// Useful when you wan't to set same container in ASP.NET and here.
        /// </param>
        /// <param name="updatesReceiver">
        /// Use it to customize how bot receiving updates.
        /// Default is <see cref="PollingUpdatesReceiver"/> and subscribe on <see cref="ITelegramBotClient.OnUpdate"/>.
        /// It will set webhook string empty, to enable polling.
        /// </param>
        public void Setup(IServiceProvider serviceProvider = null, IUpdatesReceiver updatesReceiver = null)
        {
            //?Why use IUpdatesReceiver? Why not just make ProcessUpdate method public?
            //Was decided to use interface with event to wrote more "infrastructure" code in BotManager.

            lock (_setupLocker)
            {
                try
                {
                    if (_isSetup)
                    {
                        return;
                    }

                    //Init bot context.
                    var botInfo = _bot.GetMeAsync().Result;
                    BotContext = new BotClientContext(_bot, botInfo);

                    //Set UpdateReceiver.
                    _updatesReceiver = updatesReceiver ?? new PollingUpdatesReceiver();
                    _updatesReceiver.Init(this);

                    //Build service provider.
                    string providerIndentifierForLog;
                    if (serviceProvider == null)
                    {
                        Services = _serviceCollectionWrapper.Services.BuildServiceProvider();
                        providerIndentifierForLog = "ServiceProvider builded from ServiceCollection.";
                    }
                    else
                    {
                        Services = serviceProvider;
                        providerIndentifierForLog = "Passed ServiceProvider used.";
                    }
                    _serviceCollectionWrapper = null;

                    //Resolve services needed for BotManager.
                    ResolveBotManagerServices();
                    _logger.LogTrace("Services initialized. " + providerIndentifierForLog);

                    //Not implemented.
                    IPipelineBuilder pipelineBuilder = new PipelineBuilder(Services);

                    //Register middleware.
                    UseMandatoryMiddleware(pipelineBuilder);
                    if (_pipelineBuilderAction == null)
                    {
                        throw new NullReferenceException(
                                  "Can`t init without pipeline builder configure action. " +
                                  "Probably ConfigureBuilder wasn't invoked."
                                  );
                    }
                    _pipelineBuilderAction.Invoke(pipelineBuilder);
                    _pipelineBuilderAction = null;

                    //Build pipeline.
                    _updateProcessingDelegate = pipelineBuilder.Build();
                    _isSetup = true;
                    _logger.LogTrace("Pipeline builded.");
                }
                catch (Exception ex)
                {
                    var exception = new TelegramAspException("BotManager setup exception.", ex);
                    if (_logger == null)
                    {
                        Debug.WriteLine(exception.ToString());
                    }
                    else
                    {
                        _logger.LogError(exception, "");
                    }
                    throw exception;
                }
            }
        }