Example #1
0
        public virtual IServiceCollection CreateServices()
        {
            var services = new ServiceCollection();
            var csp      = new contentapi.Services.Implementations.DefaultServiceProvider();
            var dsp      = new Randomous.EntitySystem.Implementations.DefaultServiceProvider();

            services.AddLogging(configure => configure.AddDebug());
            dsp.AddDefaultServices(
                services,
                options => options.UseSqlite(connection).EnableSensitiveDataLogging(true),
                d => d.Database.EnsureCreated());

            //EMPTY CONFIGS! Hopefully we won't need to test anything requiring these configs...
            IConfiguration config = new ConfigurationBuilder()
                                    //.AddJsonFile("appsettings.Development.json", true, true)
                                    .Build();

            csp.AddDefaultServices(services);
            csp.AddServiceConfigurations(services, config);
            services.AddSingleton(new EntityQueryableEfCoreConfig()
            {
                ConcurrentAccess = 1
            });
            //services.AddSingleton(new ModuleServiceConfig() { ModuleDataConnectionString = "Data Source=:memory:;"});
            //services.AddSingleton<ISignaler<EntityBase>, SignalSystem<EntityBase>>(); //Why must I do this every time?

            return(services);
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Add the services from entity system.
            var provider = new Randomous.EntitySystem.Implementations.DefaultServiceProvider();

            var dbConfig = new DatabaseConfig();

            Configuration.Bind(nameof(DatabaseConfig), dbConfig);

            provider.AddDefaultServices(services, options =>
            {
                if (dbConfig.DbType == "sqlite")
                {
                    options.UseSqlite(dbConfig.ConnectionString);
                }
                else if (dbConfig.DbType == "mysql")
                {
                    options.UseMySql(dbConfig.ConnectionString, options => options.EnableRetryOnFailure());
                }

                options.EnableSensitiveDataLogging(dbConfig.SensitiveLogging);
            });

            //Fix some entity system stuff. We need singletons but the default is transient
            //The IEntityProvider that we give out needs to have only a single access
            services.AddSingleton(new EntityQueryableEfCoreConfig()
            {
                ConcurrentAccess = 1
            });


            //services.AddSingleton<ISignaler<EntityBase>, SignalSystem<EntityBase>>();

            //Add our own services from contentapi
            var contentApiDefaultProvider = new Services.Implementations.DefaultServiceProvider();

            contentApiDefaultProvider.AddDefaultServices(services);
            contentApiDefaultProvider.AddServiceConfigurations(services, Configuration);
            contentApiDefaultProvider.AddConfiguration <FileControllerConfig>(services, Configuration);
            contentApiDefaultProvider.AddConfiguration <UserControllerConfig>(services, Configuration);

            //Also a singleton for the token system which we'll use for websockets
            services.AddSingleton <ITempTokenService <long>, TempTokenService <long> >();

            //A special case for websockets: we determine what the websockets will handle right here and now
            services.AddSingleton <WebSocketMiddlewareConfig>((p) =>
            {
                var websocketConfig = new WebSocketMiddlewareConfig();
                var echoer          = (WebSocketEcho)ActivatorUtilities.GetServiceOrCreateInstance(p, typeof(WebSocketEcho));
                websocketConfig.RouteHandlers.Add("testecho", echoer.Echo);
                return(websocketConfig);
            });

            //services.AddTransient(typeof(BaseSimpleControllerServices<>));
            services.AddTransient <BaseSimpleControllerServices>();

            //The rest is http stuff I think

            //Rate limiting, hope this works!
            services.AddMemoryCache();
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            services.AddCors();
            services.AddControllers()
            //.AddJsonOptions(options=> options.JsonSerializerOptions.Converters.Add(new TimeSpanToStringConverter()))
            //.AddJsonOptions(options=> options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()))
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.Converters.Add(new CustomDateTimeConverter());
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
            });

            //other rate limiting stuff
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            //Added automapper here before

            var tokenSection = Configuration.GetSection(nameof(TokenServiceConfig));

            //This is all that JWT junk. I hope it still works like this... I just copied this from my core 2.0 project
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSection.GetValue <string>("SecretKey"))),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            AddSwagger(services);

            services.AddSingleton <ICodeTimer>(p =>
            {
                if (Timer == null)
                {
                    Timer             = new SimpleCodeTimer();
                    var logger        = p.GetService <ILogger>();
                    var serviceConfig = Configuration.GetSection("ServiceTimerConfig");
                    var delay         = serviceConfig.GetValue <TimeSpan>("Delay");
                    var interval      = serviceConfig.GetValue <TimeSpan>("Interval");
                    var path          = serviceConfig.GetValue <string>("ProfilerPath");
                    logger.Information($"Starting profiler: Delay {delay} Interval {interval} Path {path}");

                    ServiceTimer = new Timer(x =>
                    {
                        try { Timer.FlushData(path).Wait(); }
                        catch (Exception ex) { logger.Warning($"Couldn't flush profiler: {ex}"); }
                    }, null, delay, interval);
                }

                return(Timer);
            });
        }