예제 #1
0
            public override void Configure(Container container)
            {
                var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);

                container.Register <IDbConnectionFactory>(dbFactory);

                container.Register <IAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));
                container.Resolve <IAuthRepository>().InitSchema();

                Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                            new IAuthProvider[] {
                    new ApiKeyAuthProvider(AppSettings)
                    {
                        RequireSecureConnection = false
                    },
                })
                {
                    IncludeRegistrationService = true,
                });

                GlobalRequestFilters.Add((req, res, dto) =>
                {
                    LastApiKey = req.GetApiKey();
                });
            }
예제 #2
0
        public override void Configure(Container container)
        {
            var dbFactory = new OrmLiteConnectionFactory(
                "~/App_Data/master.sqlite".MapAbsolutePath(), SqliteDialect.Provider);

            const int noOfTennants = 3;

            container.Register <IDbConnectionFactory>(c =>
                                                      new MultiTenantDbFactory(dbFactory));

            var multiDbFactory = (MultiTenantDbFactory)
                                 container.Resolve <IDbConnectionFactory>();

            using (var db = multiDbFactory.OpenTenant())
                InitDb(db, "MASTER", "Masters inc.");

            noOfTennants.Times(i =>
            {
                var tenantId = "T0" + (i + 1);
                using (var db = multiDbFactory.OpenTenant(tenantId))
                    InitDb(db, tenantId, "ACME {0} inc.".Fmt(tenantId));
            });

            GlobalRequestFilters.Add((req, res, dto) =>
            {
                var forTennant = dto as IForTenant;
                if (forTennant != null)
                {
                    RequestContext.Instance.Items.Add("TenantId", forTennant.TenantId);
                }
            });
        }
예제 #3
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            //Config examples
            //this.Plugins.Add(new PostmanFeature());
            //this.Plugins.Add(new CorsFeature());

            Plugins.Add(new CorsFeature());

            Plugins.Add(new SessionFeature());

            Plugins.Add(new RegistrationFeature());

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[]
            {
                new BasicAuthProvider()
            }));

            var userRepo = new InMemoryAuthRepository();

            container.Register <IAuthRepository>(userRepo);

            container.Register <ICacheClient>(new MemoryCacheClient());

            container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
                                                          "Data Source=.; Initial Catalog=VotingApp; Integrated Security=True", SqlServerDialect.Provider
                                                          ));

            GlobalRequestFilters.Add((req, res, dto) => req.ResponseContentType = MimeTypes.Json);
        }
        public override void Configure(Container container)
        {
            GlobalRequestFilters.Add((req, res, dto) =>
            {
                var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                if (autoBatchIndex != null)
                {
                    res.RemoveHeader("GlobalRequestFilterAutoBatchIndex");
                    res.AddHeader("GlobalRequestFilterAutoBatchIndex", autoBatchIndex);
                }
            });

            GlobalResponseFilters.Add((req, res, dto) =>
            {
                var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();

                if (autoBatchIndex != null)
                {
                    if (dto is IMeta response)
                    {
                        response.Meta = new Dictionary <string, string>
                        {
                            ["GlobalResponseFilterAutoBatchIndex"] = autoBatchIndex
                        };
                    }
                }
            });
        }
예제 #5
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new NLogFactory();

            GlobalRequestFilters.Add((req, resp, requestDto) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Debug(string.Format(
                              "REQ {0}: {1} {2} {3} {4} {5}\n",
                              DateTimeOffset.Now.Ticks, req.Verb,
                              req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent));
            });
            GlobalResponseFilters.Add((req, resp, requestDto) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Debug(string.Format(
                              "RES {0}: {1} {2}\n",
                              DateTimeOffset.Now.Ticks, resp.StatusCode, resp.ContentType));
            });
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Error(exception);
                return(DtoUtils.CreateErrorResponse(request, exception));
            });


            var config = new HostConfig();

            config.DebugMode             = true; //Show StackTraces in service responses during development
            config.WriteErrorsToResponse = true;
            config.ReturnsInnerException = true;
            SetConfig(config);
        }
 public override void Configure(Container container)
 {
     GlobalRequestFilters.Add((request, response, dto) =>
     {
         var holder   = container.Resolve <ValueHolder>();
         holder.Value = (dto as GetValue).Value;
     });
 }
예제 #7
0
            public override void Configure(Container container)
            {
                Plugins.Add(new ValidationFeature());
                Plugins.Add(new GrpcFeature(App));

                container.Register <IAuthRepository>(new InMemoryAuthRepository());
                container.Resolve <IAuthRepository>().InitSchema();

                Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                            new IAuthProvider[]
                {
                    new BasicAuthProvider(),
                    new CredentialsAuthProvider(),
                    new JwtAuthProvider
                    {
                        AuthKey = AuthKey,
                        RequireSecureConnection = false,
                        AllowInQueryString      = true,
                        AllowInFormData         = true,
                        IncludeJwtInConvertSessionToTokenResponse = true,
                    },
                    new ApiKeyAuthProvider(AppSettings)
                    {
                        RequireSecureConnection = false
                    },
                }));

                Plugins.Add(new RegistrationFeature());

                GlobalRequestFilters.Add((req, res, dto) =>
                {
                    LastApiKey = req.GetApiKey();
                });

                AfterInitCallbacks.Add(host => {
                    var authRepo = GetAuthRepository();
                    (authRepo as InMemoryAuthRepository).Clear();

                    authRepo.CreateUserAuth(new UserAuth
                    {
                        Id          = userId.ToInt(),
                        UserName    = Username,
                        FirstName   = "First",
                        LastName    = "Last",
                        DisplayName = "Display",
                    }, Password);

                    apiRepo            = (IManageApiKeys)container.Resolve <IAuthRepository>();
                    var apiKeyProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                    var apiKeys        = apiKeyProvider.GenerateNewApiKeys(userId);
                    using (authRepo as IDisposable)
                    {
                        apiRepo.StoreAll(apiKeys);
                    }
                    liveKey = apiKeys.First(x => x.Environment == "live");
                    testKey = apiKeys.First(x => x.Environment == "test");
                });
            }
예제 #8
0
        public override void Configure(Container container)
        {
            GlobalRequestFilters.Add((rew, res, dto) =>
                                     ReplyAllRequestAttribute.AssertSingleDto(dto));

            GlobalResponseFilters.Add((rew, res, dto) =>
                                      ReplyAllResponseAttribute.AssertSingleDto(dto));

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
        }
예제 #9
0
        public override void Configure()
        {
            var requestFilters = _appHost.GetExports <IRequestFilter>().ToList();

            foreach (var filter in requestFilters)
            {
                GlobalRequestFilters.Add(filter.Filter);
            }

            GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
        }
예제 #10
0
            public override void Configure(Container container)
            {
                Plugins.Add(new ValidationFeature());
                Plugins.Add(new GrpcFeature(App));

                GlobalRequestFilters.Add((req, res, dto) => {
                    if (dto is ThrowCustom)
                    {
                        throw new CustomException();
                    }
                });
            }
            public override void Configure(Container container)
            {
                RegisterService <GetFileService>();

                Plugins.Add(new ValidationFeature());
                Plugins.Add(new GrpcFeature(App));

                GlobalRequestFilters.Add((req, res, dto) => {
                    if (dto is ServiceStack.Extensions.Tests.ThrowCustom)
                    {
                        throw new CustomException();
                    }
                });
            }
예제 #12
0
 public override void Configure(Container container)
 {
     GlobalRequestFilters.Add((req, res, dto) =>
     {
         req.Items[Keywords.Session] = new AuthUserSession
         {
             UserAuthId   = "1",
             Language     = "en",
             PhoneNumber  = "*****",
             FirstName    = "Test",
             LastName     = "User",
             PrimaryEmail = "*****@*****.**",
             UserAuthName = "testuser",
         };
     });
 }
예제 #13
0
    public override void Configure(Container container)
    {
        GlobalRequestFilters.Add((req, res, requestDto) => {
            var sessionId = req.GetCookieValue("user-session");
            if (sessionId == null)
            {
                res.ReturnAuthRequired();
            }
        });

        RegisterTypedRequestFilter <Resource>((req, res, dto) =>
        {
            var route = req.GetRoute();
            if (route?.Path == "/tenant/{Name}/resource")
            {
                dto.SubResourceName = "CustomResource";
            }
        });
    }
예제 #14
0
            public override void Configure(Container container)
            {
                JsConfig.Init(new Text.Config
                {
                    TextCase = TextCase.CamelCase,
                });

                SetConfig(new HostConfig
                {
                    DebugMode = false,
                });

                Plugins.Add(new ProtoBufFormat());

                GlobalRequestFilters.Add((req, res, dto) => {
                    if (dto is UncatchedException || dto is UncatchedExceptionAsync)
                    {
                        throw new ArgumentException();
                    }
                });

                //Custom global uncaught exception handling strategy
                this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
                {
                    res.WriteAsync($"UncaughtException {ex.GetType().Name}")
                    .ContinueWith(t => res.EndRequest(skipHeaders: true));
                });

                this.ServiceExceptionHandlers.Add((httpReq, request, ex) =>
                {
                    if (request is UncatchedException || request is UncatchedExceptionAsync)
                    {
                        throw ex;
                    }

                    if (request is CaughtException || request is CaughtExceptionAsync)
                    {
                        return(DtoUtils.CreateErrorResponse(request, new ArgumentException("ExceptionCaught")));
                    }

                    return(null);
                });
            }
예제 #15
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new NLogFactory();

            GlobalRequestFilters.Add((req, resp, requestDto) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Info(string.Format(
                             "REQ {0}: {1} {2} {3} {4} {5} \n",
                             DateTimeOffset.Now.Ticks, req.Verb,
                             req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent));
            });
            GlobalResponseFilters.Add((req, resp, requestDto) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Info(string.Format(
                             "RES {0}: {1} {2}\n",
                             DateTimeOffset.Now.Ticks, resp.StatusCode, resp.ContentType));
            });

            this.ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Error(exception);
                //call default exception handler or prepare your own custom response
                return(DtoUtils.CreateErrorResponse(request, exception));
            });

            /*
             * Plugins.Add (new AuthFeature (() => new AuthUserSession (),
             *                            new IAuthProvider[] {new BasicAuthProvider ()})
             *           );
             * Plugins.Add (new RegistrationFeature ());
             * //Plugins.Add(new RequestLogsFeature());
             *
             * container.Register<ICacheClient>(new MemoryCacheClient());
             * var userRep = new InMemoryAuthRepository();
             * container.Register<IUserAuthRepository>(userRep);
             */
            var config = new HostConfig();

            config.DebugMode             = true; //Show StackTraces in service responses during development
            config.WriteErrorsToResponse = true;
            config.ReturnsInnerException = true;
            SetConfig(config);
        }
예제 #16
0
 protected void PopulateArrayFilters()
 {
     PreRequestFiltersArray                = PreRequestFilters.ToArray();
     RequestConvertersArray                = RequestConverters.ToArray();
     ResponseConvertersArray               = ResponseConverters.ToArray();
     GlobalRequestFiltersArray             = GlobalRequestFilters.ToArray();
     GlobalRequestFiltersAsyncArray        = GlobalRequestFiltersAsync.ToArray();
     GlobalResponseFiltersArray            = GlobalResponseFilters.ToArray();
     GlobalResponseFiltersAsyncArray       = GlobalResponseFiltersAsync.ToArray();
     GlobalMessageRequestFiltersArray      = GlobalMessageRequestFilters.ToArray();
     GlobalMessageRequestFiltersAsyncArray = GlobalMessageRequestFiltersAsync.ToArray();
     GlobalMessageResponseFiltersArray     = GlobalMessageResponseFilters.ToArray();
     RawHttpHandlersArray             = RawHttpHandlers.ToArray();
     CatchAllHandlersArray            = CatchAllHandlers.ToArray();
     GatewayRequestFiltersArray       = GatewayRequestFilters.ToArray();
     GatewayRequestFiltersAsyncArray  = GatewayRequestFiltersAsync.ToArray();
     GatewayResponseFiltersArray      = GatewayResponseFilters.ToArray();
     GatewayResponseFiltersAsyncArray = GatewayResponseFiltersAsync.ToArray();
 }
            public override void Configure(Container container)
            {
                SetConfig(new HostConfig {
                    DebugMode = false
                });

                OnEndRequestCallbacks.Add(req => {
                    Interlocked.Increment(ref OnEndRequestCallbacksCount);
                });

                GlobalRequestFilters.Add((req, res, dto) => {
                    if (dto is UncatchedException || dto is UncatchedExceptionAsync)
                    {
                        throw new ArgumentException();
                    }
                });

                //Custom global uncaught exception handling strategy
                this.UncaughtExceptionHandlersAsync.Add(async(req, res, operationName, ex) =>
                {
                    await res.WriteAsync($"UncaughtException {ex.GetType().Name}");
                    res.EndRequest(skipHeaders: true);
                });

                this.ServiceExceptionHandlersAsync.Add(async(httpReq, request, ex) =>
                {
                    await Task.Yield();

                    if (request is UncatchedException || request is UncatchedExceptionAsync)
                    {
                        throw ex;
                    }

                    if (request is CaughtException || request is CaughtExceptionAsync)
                    {
                        return(DtoUtils.CreateErrorResponse(request, new ArgumentException("ExceptionCaught")));
                    }

                    return(null);
                });
            }
예제 #18
0
        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/Views/TestErrorNotFound");

            var nativeTypes = this.GetPlugin <NativeTypesFeature>();

            nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek));
            nativeTypes.MetadataTypesConfig.IgnoreTypes.Add(typeof(IgnoreInMetadataConfig));
            //nativeTypes.MetadataTypesConfig.GlobalNamespace = "Check.ServiceInterface";

            // Change ServiceStack configuration
            this.SetConfig(new HostConfig
            {
                DebugMode = true,
                //UseHttpsLinks = true,
                AppendUtf8CharsetOnContentTypes = { MimeTypes.Html },
                UseCamelCase    = true,
                AdminAuthSecret = "secretz",
                //HandlerFactoryPath = "CheckWeb", //when hosted on IIS
                //AllowJsConfig = false,

                // Set to return JSON if no request content type is defined
                // e.g. text/html or application/json
                //DefaultContentType = MimeTypes.Json,
                // Disable SOAP endpoints
                //EnableFeatures = Feature.All.Remove(Feature.Soap)
                //EnableFeatures = Feature.All.Remove(Feature.Metadata)
            });

            container.Register <IServiceClient>(c =>
                                                new JsonServiceClient("http://localhost:55799/"));

            Plugins.Add(new TemplatePagesFeature
            {
                EnableDebugTemplateToAll = true
            });

            //            Plugins.Add(new SoapFormat());

            //ProxyFetureTests
            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/proxy/test"),
                            resolveUrl: req => "http://test.servicestack.net".CombineWith(req.RawUrl.Replace("/test", "/"))));

            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/techstacks"),
                            resolveUrl: req => "http://techstacks.io".CombineWith(req.RawUrl.Replace("/techstacks", "/"))));

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });

            Plugins.Add(new AutoQueryDataFeature()
                        .AddDataSource(ctx => ctx.MemorySource(GetRockstars())));

            Plugins.Add(new AdminFeature());

            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] { "http://localhost", "http://localhost:8080", "http://localhost:56500", "http://test.servicestack.net", "http://null.jsbin.com" },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization, X-Args"));

            Plugins.Add(new ServerEventsFeature
            {
                LimitToAuthenticatedUsers = true
            });

            GlobalRequestFilters.Add((req, res, dto) =>
            {
                if (dto is AlwaysThrowsGlobalFilter)
                {
                    throw new Exception(dto.GetType().Name);
                }
            });

            Plugins.Add(new RequestLogsFeature
            {
                RequestLogger = new CsvRequestLogger(),
            });

            Plugins.Add(new DynamicallyRegisteredPlugin());

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
            //container.Register<IDbConnectionFactory>(
            //    new OrmLiteConnectionFactory("Server=localhost;Database=test;User Id=test;Password=test;", SqlServerDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Rockstar>();
                db.InsertAll(GetRockstars());

                db.DropAndCreateTable <AllTypes>();
                db.Insert(new AllTypes
                {
                    Id       = 1,
                    Int      = 2,
                    Long     = 3,
                    Float    = 1.1f,
                    Double   = 2.2,
                    Decimal  = 3.3m,
                    DateTime = DateTime.Now,
                    Guid     = Guid.NewGuid(),
                    TimeSpan = TimeSpan.FromMilliseconds(1),
                    String   = "String"
                });
            }

            Plugins.Add(new MiniProfilerFeature());

            var dbFactory = (OrmLiteConnectionFactory)container.Resolve <IDbConnectionFactory>();

            dbFactory.RegisterConnection("SqlServer",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Database=test;User Id=test;Password=test;",
                                             SqlServerDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            dbFactory.RegisterConnection("pgsql",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
                                             PostgreSqlDialect.Provider));

            using (var db = dbFactory.OpenDbConnection("pgsql"))
            {
                db.DropAndCreateTable <Rockstar>();
                db.DropAndCreateTable <PgRockstar>();

                db.Insert(new Rockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Connection", Age = 1
                });
                db.Insert(new PgRockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Named Connection", Age = 1
                });
            }

            //this.GlobalHtmlErrorHttpHandler = new RazorHandler("GlobalErrorHandler.cshtml");

            // Configure JSON serialization properties.
            this.ConfigureSerialization(container);

            // Configure ServiceStack database connections.
            this.ConfigureDataConnection(container);

            // Configure ServiceStack Authentication plugin.
            this.ConfigureAuth(container);

            // Configure ServiceStack Fluent Validation plugin.
            this.ConfigureValidation(container);

            // Configure ServiceStack Razor views.
            this.ConfigureView(container);

            this.StartUpErrors.Add(new ResponseStatus("Mock", "Startup Error"));

            //PreRequestFilters.Add((req, res) =>
            //{
            //    if (req.PathInfo.StartsWith("/metadata") || req.PathInfo.StartsWith("/swagger-ui"))
            //    {
            //        var session = req.GetSession();
            //        if (!session.IsAuthenticated)
            //        {
            //            res.StatusCode = (int)HttpStatusCode.Unauthorized;
            //            res.EndRequest();
            //        }
            //    }
            //});
        }
예제 #19
0
        // public override void HttpCookieFilter(HttpCookie cookie)
        // {
        //     cookie.SameSite = SameSiteMode.None;
        // }

        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
//            EnableBuffering();

            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/Views/TestErrorNotFound");

            // Change ServiceStack configuration
            SetConfig(new HostConfig
            {
                DebugMode = true,
                //UseHttpsLinks = true,
                AppendUtf8CharsetOnContentTypes = { MimeTypes.Html },
                CompressFilesWithExtensions     = { "js", "css" },
                UseCamelCase    = true,
                AdminAuthSecret = "secretz",
                //HandlerFactoryPath = "CheckWeb", //when hosted on IIS
                //AllowJsConfig = false,

                // Set to return JSON if no request content type is defined
                // e.g. text/html or application/json
                //DefaultContentType = MimeTypes.Json,
                // Disable SOAP endpoints
                //EnableFeatures = Feature.All.Remove(Feature.Soap)
                //EnableFeatures = Feature.All.Remove(Feature.Metadata)
            });

            container.Register <IServiceClient>(c =>
                                                new JsonServiceClient("http://localhost:55799/"));

            Plugins.Add(new SharpPagesFeature
            {
                MetadataDebugAdminRole = RoleNames.AllowAnyUser,
                ScriptAdminRole        = RoleNames.AllowAnon,
            });

            //ProxyFetureTests
            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/proxy/test"),
                            resolveUrl: req => "http://test.servicestack.net".CombineWith(req.RawUrl.Replace("/test", "/"))));

            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/techstacks"),
                            resolveUrl: req => "http://techstacks.io".CombineWith(req.RawUrl.Replace("/techstacks", "/"))));

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });

            Plugins.Add(new AutoQueryDataFeature()
                        .AddDataSource(ctx => ctx.MemorySource(GetRockstars())));

            //Plugins.Add(new AdminFeature());

            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] { "http://localhost", "http://localhost:8080", "http://localhost:56500", "http://test.servicestack.net", "http://null.jsbin.com" },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization, X-Args"));

            Plugins.Add(new ServerEventsFeature
            {
                LimitToAuthenticatedUsers = true
            });

            GlobalRequestFilters.Add((req, res, dto) =>
            {
                if (dto is AlwaysThrowsGlobalFilter)
                {
                    throw new Exception(dto.GetType().Name);
                }
            });

            Plugins.Add(new RequestLogsFeature
            {
                RequestLogger          = new CsvRequestLogger(),
                EnableResponseTracking = true
            });

            Plugins.Add(new DynamicallyRegisteredPlugin());

            var nativeTypes = GetPlugin <NativeTypesFeature>();

            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(DisplayAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(DisplayColumnAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(DisplayFormatAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(DataTypeAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(EditableAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(ServiceStack.DataAnnotations.PrimaryKeyAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(ServiceStack.DataAnnotations.AutoIncrementAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(ServiceStack.DataAnnotations.AutoIdAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(System.ComponentModel.BindableAttribute));
            nativeTypes.MetadataTypesConfig.ExportAttributes.Add(typeof(AssociationAttribute));

            nativeTypes.ExportAttribute <DisplayAttribute>(x =>
            {
                var metadata = nativeTypes.GetGenerator().ToMetadataAttribute(x);
                try
                {
                    var attr = (DisplayAttribute)x;
                    if (attr.GetAutoGenerateField() == null || (attr.GetAutoGenerateField().HasValue&& !attr.GetAutoGenerateField().Value))
                    {
                        metadata.Args.Add(new MetadataPropertyType {
                            Name          = nameof(DisplayAttribute.AutoGenerateField),
                            TypeNamespace = "System",
                            Type          = nameof(Boolean),
                            Value         = "false"
                        });
                    }
                    return(metadata);
                }
                catch (Exception ex)
                {
                    throw;
                }
            });


//            container.Register<IDbConnectionFactory>(
//                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
//            //container.Register<IDbConnectionFactory>(
//            //    new OrmLiteConnectionFactory("Server=localhost;Database=test;User Id=test;Password=test;", SqlServerDialect.Provider));
//
//            using (var db = container.Resolve<IDbConnectionFactory>().Open())
//            {
//                db.DropAndCreateTable<Rockstar>();
//                db.InsertAll(GetRockstars());
//
//                db.DropAndCreateTable<AllTypes>();
//                db.Insert(new AllTypes
//                {
//                    Id = 1,
//                    Int = 2,
//                    Long = 3,
//                    Float = 1.1f,
//                    Double = 2.2,
//                    Decimal = 3.3m,
//                    DateTime = DateTime.Now,
//                    Guid = Guid.NewGuid(),
//                    TimeSpan = TimeSpan.FromMilliseconds(1),
//                    String = "String"
//                });
//            }
//
//            Plugins.Add(new MiniProfilerFeature());
//
//            var dbFactory = (OrmLiteConnectionFactory)container.Resolve<IDbConnectionFactory>();
//            dbFactory.RegisterConnection("SqlServer",
//                new OrmLiteConnectionFactory(
//                    "Server=localhost;Database=test;User Id=test;Password=test;",
//                    SqlServerDialect.Provider)
//                {
//                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
//                });
//
//            dbFactory.RegisterConnection("pgsql",
//                new OrmLiteConnectionFactory(
//                    Environment.GetEnvironmentVariable("PGSQL_CONNECTION") ??
//                    "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
//                    PostgreSqlDialect.Provider));
//
//            using (var db = dbFactory.OpenDbConnection("pgsql"))
//            {
//                db.DropAndCreateTable<Rockstar>();
//                db.DropAndCreateTable<PgRockstar>();
//
//                db.Insert(new Rockstar { Id = 1, FirstName = "PostgreSQL", LastName = "Connection", Age = 1 });
//                db.Insert(new PgRockstar { Id = 1, FirstName = "PostgreSQL", LastName = "Named Connection", Age = 1 });
//            }

            //this.GlobalHtmlErrorHttpHandler = new RazorHandler("GlobalErrorHandler.cshtml");

            // Configure JSON serialization properties.
            this.ConfigureSerialization(container);

            // Configure ServiceStack database connections.
            this.ConfigureDataConnection(container);

            // Configure ServiceStack Authentication plugin.
            this.ConfigureAuth(container);

            // Configure ServiceStack Fluent Validation plugin.
            this.ConfigureValidation(container);

            // Configure ServiceStack Razor views.
            this.ConfigureView(container);

            this.StartUpErrors.Add(new ResponseStatus("Mock", "Startup Error"));

            //PreRequestFilters.Add((req, res) =>
            //{
            //    if (req.PathInfo.StartsWith("/metadata") || req.PathInfo.StartsWith("/swagger-ui"))
            //    {
            //        var session = req.GetSession();
            //        if (!session.IsAuthenticated)
            //        {
            //            res.StatusCode = (int)HttpStatusCode.Unauthorized;
            //            res.EndRequest();
            //        }
            //    }
            //});

            Plugins.Add(new ProtoBufFormat());
        }
예제 #20
0
        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            var nativeTypes = this.GetPlugin <NativeTypesFeature>();

            nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek));
            nativeTypes.MetadataTypesConfig.IgnoreTypes.Add(typeof(IgnoreInMetadataConfig));
            //nativeTypes.MetadataTypesConfig.GlobalNamespace = "Check.ServiceInterface";

            // Change ServiceStack configuration
            this.SetConfig(new HostConfig
            {
                DebugMode = true,
                //UseHttpsLinks = true,
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    MimeTypes.Html
                },
                UseCamelCase = true,
                //AllowJsConfig = false,

                // Set to return JSON if no request content type is defined
                // e.g. text/html or application/json
                //DefaultContentType = MimeTypes.Json,
                // Disable SOAP endpoints
                //EnableFeatures = Feature.All.Remove(Feature.Soap)
                //EnableFeatures = Feature.All.Remove(Feature.Metadata)
            });

            container.Register <IServiceClient>(c =>
                                                new JsonServiceClient("http://localhost:55799/")
            {
                CaptureSynchronizationContext = true,
            });

            //ProxyFetureTests
            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/test"),
                            resolveUrl: req => "http://test.servicestack.net".CombineWith(req.RawUrl.Replace("/test", "/"))));

            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/techstacks"),
                            resolveUrl: req => "http://techstacks.io".CombineWith(req.RawUrl.Replace("/techstacks", "/"))));

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });

            Plugins.Add(new AutoQueryDataFeature()
                        .AddDataSource(ctx => ctx.MemorySource(GetRockstars())));

            Plugins.Add(new AdminFeature());

            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());

            GlobalRequestFilters.Add((req, res, dto) =>
            {
                if (dto is AlwaysThrowsGlobalFilter)
                {
                    throw new Exception(dto.GetType().Name);
                }
            });

            Plugins.Add(new RequestLogsFeature {
                RequestLogger = new CsvRequestLogger(),
            });

            Plugins.Add(new DynamicallyRegisteredPlugin());

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Rockstar>();
                db.InsertAll(GetRockstars());
            }

            var dbFactory = (OrmLiteConnectionFactory)container.Resolve <IDbConnectionFactory>();

            dbFactory.RegisterConnection("SqlServer",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Database=test;User Id=test;Password=test;",
                                             SqlServerDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            dbFactory.RegisterConnection("pgsql",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
                                             PostgreSqlDialect.Provider));

            using (var db = dbFactory.OpenDbConnection("pgsql"))
            {
                db.DropAndCreateTable <Rockstar>();
                db.DropAndCreateTable <PgRockstar>();

                db.Insert(new Rockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Connection", Age = 1
                });
                db.Insert(new PgRockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Named Connection", Age = 1
                });
            }

            //this.GlobalHtmlErrorHttpHandler = new RazorHandler("GlobalErrorHandler.cshtml");

            // Configure JSON serialization properties.
            this.ConfigureSerialization(container);

            // Configure ServiceStack database connections.
            this.ConfigureDataConnection(container);

            // Configure ServiceStack Authentication plugin.
            this.ConfigureAuth(container);

            // Configure ServiceStack Fluent Validation plugin.
            this.ConfigureValidation(container);

            // Configure ServiceStack Razor views.
            this.ConfigureView(container);

            this.StartUpErrors.Add(new ResponseStatus("Mock", "Startup Error"));
        }
예제 #21
0
파일: AppHost.cs 프로젝트: NetCoreApps/Test
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        /// <param name="container"></param>
        public override void Configure(Container container)
        {
            // this.GlobalHtmlErrorHttpHandler = new RazorHandler("/error");
            CSharpGenerator.UseNullableAnnotations = true;

            SetConfig(new HostConfig
            {
                AdminAuthSecret    = "secretz",
                DebugMode          = HostingEnvironment.IsDevelopment(),
                UseSameSiteCookies = true,
                Return204NoContentForEmptyResponse = true,
            });

            container.Register <IRedisClientsManager>(c =>
                                                      new RedisManagerPool("localhost:6379"));
            container.Register(c => c.Resolve <IRedisClientsManager>().GetCacheClient());

            //container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
            //    AppSettings.GetString("AppDb"), PostgreSqlDialect.Provider));

            container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
                                                          ":memory:", SqliteDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Logger>();
            }

            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = AppSettings.Get("UseDistinctRoleTables", true),
            });

            var authRepo = (OrmLiteAuthRepository)container.Resolve <IAuthRepository>();

            authRepo.DropAndReCreateTables();

            CreateUser(authRepo, 1, "test", "test", new List <string> {
                "TheRole"
            }, new List <string> {
                "ThePermission"
            });
            CreateUser(authRepo, 2, "test2", "test2");
            CreateUser(authRepo, 2, "admin", "test", new List <string> {
                RoleNames.Admin
            });

            Plugins.Add(new PostmanFeature());

            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] {
                "http://localhost", "http://localhost:8080", "http://localhost:56500", "http://test.servicestack.net",
                "http://null.jsbin.com", "http://plnkr.co", "http://run.plnkr.co"
            },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization, X-Args"));

            Plugins.Add(new RequestLogsFeature
            {
                //RequestLogger = new RedisRequestLogger(container.Resolve<IRedisClientsManager>()),
            });
            // Plugins.Add(new RazorFormat());

            GlobalRequestFilters.Add((req, res, dto) => {
                var msg = $"{req.Verb} {req.PathInfo} > {req.ContentType} < {string.Join(',', req.AcceptTypes)}";
                msg.Print();
            });

            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[]
            {
                new JwtAuthProvider(AppSettings)
                {
                    AllowInQueryString = true,
                },
                new BasicAuthProvider(AppSettings),
                new CredentialsAuthProvider(AppSettings),
                new TwitterAuthProvider(AppSettings),       //Sign-in with Twitter
                new FacebookAuthProvider(AppSettings),      //Sign-in with Facebook
                new GithubAuthProvider(AppSettings),        //Sign-in with GitHub
            })
            {
                // AllowGetAuthenticateRequests = req => true,
                IncludeRegistrationService = true,
                IncludeAssignRoleServices  = true,
            });

            Plugins.Add(new OpenApiFeature());
            // Plugins.Add(new ValidationFeature());
            Plugins.Add(new AutoQueryFeature
            {
                MaxLimit = 1000,
            });

            container.RegisterValidators(typeof(ThrowValidationValidator).Assembly);

            JavaGenerator.AddGsonImport = true;
            var nativeTypes = this.GetPlugin <NativeTypesFeature>();

            nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek));

            Plugins.Add(new SharpPagesFeature());

            container.RegisterAutoWiredAs <MemoryChatHistory, IChatHistory>();
            Plugins.Add(new ServerEventsFeature
            {
                // LimitToAuthenticatedUsers = true,
            });

            TypeScriptGenerator.ReturnTypeAliases[typeof(byte[]).Name] = "Uint8Array";
        }
예제 #22
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            Plugins.Add(new SharpPagesFeature()); // enable server-side rendering, see: https://sharpscript.net/docs/sharp-pages

            // This is already done for you however in many cases you may want to add
            // your own custom items that will be a part of this cascading app settings provider
            MultiAppSettingsBuilder multiAppSettingsBuilder = new MultiAppSettingsBuilder();

            multiAppSettingsBuilder
            .AddNetCore(_coreConfig);     // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#default-configuration

            // You can add text files or your own dictionary of custom values if you want

            AppSettings = multiAppSettingsBuilder.Build();
            JsConfig.TreatEnumAsInteger = true;

            SetConfig(new HostConfig
            {
                UseCamelCase                   = true,
                UseSameSiteCookies             = true,
                AddRedirectParamsToQueryString = true,
                DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), HostingEnvironment.IsDevelopment()),
            });

            // for our app we will use an inmemory database.  This can be replaced with no
            // code changes for sql server, mysql or any of the ormlite providers

            Plugins.Add(new AutoQueryDataFeature()
            {
                MaxLimit = int.MaxValue
            });

            Plugins.Add(new AdminFeature());
            container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.CreateTableIfNotExists <PostLog>();
            }



            GatewayRequestFilters.Add((req, dto) =>
            {
                if (dto is PostRequest || dto is PostQueryRequest)
                {
                    using (var db = Resolve <IDbConnectionFactory>().Open())
                    {
                        using (var trans = db.OpenTransaction())
                        {
                            db.Insert <PostLog>(new PostLog()
                            {
                                EntryDate   = DateTime.UtcNow,
                                Identifier  = (dto is PostRequest) ? ((PostRequest)dto).Id : string.Empty,
                                RequestType = dto.ToString(),
                                FilterType  = FilterType.GatewayFilter
                            });
                            trans.Commit();
                        }
                    }
                }
            });

            GlobalRequestFilters.Add((req, res, dto) =>
            {
                if (dto is PostRequest || dto is PostQueryRequest)
                {
                    using (var db = Resolve <IDbConnectionFactory>().Open())
                    {
                        using (var trans = db.OpenTransaction()) {
                            db.Insert <PostLog>(new PostLog()
                            {
                                EntryDate   = DateTime.UtcNow,
                                Identifier  = (dto is PostRequest) ? ((PostRequest)dto).Id : string.Empty,
                                RequestType = dto.GetType().ToString(),
                                FilterType  = FilterType.RequestFilter
                            });
                            trans.Commit();
                        }
                    }
                }
            });

            container.AddTransient <IServiceGatewayFactory>(() => new CustomServiceGatewayFactory());
        }
예제 #23
0
    // Configure your AppHost with the necessary configuration and dependencies your App needs
    public override void Configure(Container container)
    {
        // JsConfig.Init(new ServiceStack.Text.Config {
        //     IncludeNullValues = true,
        //     TextCase = TextCase.PascalCase
        // });
        SetConfig(new HostConfig
        {
            //DebugMode = false,
            DebugMode       = true,
            AdminAuthSecret = "secret",
        });

        var memFs = GetVirtualFileSource <MemoryVirtualFiles>();
        var files = VirtualFiles.GetDirectory("custom").GetAllFiles();

        files.Each(file => memFs.WriteFile($"locode/{file.Name}", file));
        GlobalRequestFilters.Add((req, res, dto) => {
            files.Each(file => memFs.WriteFile($"locode/{file.Name}", file));
        });

        ConfigurePlugin <UiFeature>(feature => {
            Console.WriteLine(@"ConfigurePlugin<UiFeature>...");
            feature.HtmlModules.Add(new("/modules/forms", "/forms"));

            feature.Module.Configure((appHost, module) =>
            {
                module.VirtualFiles = appHost.VirtualFiles;
                module.DirPath      = module.DirPath.Replace("/modules", "");
            });
            feature.Handlers.Cast <SharedFolder>().Each(x =>
                                                        x.SharedDir = x.SharedDir.Replace("/modules", ""));
        });

        // Not needed in `dotnet watch` and in /wwwroot/modules/ui which can use _framework/aspnetcore-browser-refresh.js"
        Plugins.AddIfDebug(new HotReloadFeature
        {
            VirtualFiles   = VirtualFiles,
            DefaultPattern = "*.html;*.js;*.css"
        });
        //Plugins.Add(new PostmanFeature());

        var uploadVfs  = new FileSystemVirtualFiles(TalentBlazorWwwRootDir);
        var appDataVfs = new FileSystemVirtualFiles(TalentBlazorAppDataDir);

        Plugins.Add(new FilesUploadFeature(
                        new UploadLocation("profiles", uploadVfs, allowExtensions: FileExt.WebImages,
                                           resolvePath: ctx => $"/profiles/{ctx.FileName}"),

                        new UploadLocation("game_items", appDataVfs, allowExtensions: FileExt.WebImages),

                        new UploadLocation("files", GetVirtualFileSource <FileSystemVirtualFiles>(),
                                           resolvePath: ctx => $"/files/{ctx.FileName}"),

                        new UploadLocation("users", uploadVfs, allowExtensions: FileExt.WebImages,
                                           resolvePath: ctx => $"/profiles/users/{ctx.UserAuthId}.{ctx.FileExtension}"),

                        new UploadLocation("applications", appDataVfs, maxFileCount: 3, maxFileBytes: 10_000_000,
                                           resolvePath: ctx => ctx.GetLocationPath((ctx.Dto is CreateJobApplication create
                    ? $"job/{create.JobId}"
                    : $"app/{ctx.Dto.GetId()}") + $"/{ctx.DateSegment}/{ctx.FileName}"),
                                           readAccessRole: RoleNames.AllowAnon, writeAccessRole: RoleNames.AllowAnon)
                        ));

        Metadata.ForceInclude = new() {
            typeof(GetAccessToken)
        };
        Plugins.Add(new ServiceStack.Api.OpenApi.OpenApiFeature());
    }
예제 #24
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new OpenApiFeature());

            SetConfig(new HostConfig
            {
                DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false),
#if DEBUG
                AdminAuthSecret = "adm1nSecret", // Enable Admin Access with ?authsecret=adm1nSecret
#endif
            });

            container.Register <IList <GroupModel> >(new List <GroupModel>());

            GlobalRequestFilters.Add((req, resp, reqDto) =>
            {
                req.Items.Add("BeginTimestamp", DateTime.Now);
            });
            GlobalResponseFilters.Add((req, resp, respDto) =>
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine($"**************** {nameof(GlobalResponseFilters)} ****************");
                //Console.WriteLine($"***** req: {req.ToSafeJson()}");
                Console.WriteLine();

                var beginTimestamp = req.Items["BeginTimestamp"];
                var endTimestamp   = DateTime.Now;

                Console.WriteLine($"=====> Request at [{beginTimestamp}]");
                if (req.IsAuthenticated())
                {
                    var session    = req.SessionAs <CustomUserSession>();
                    var authRepo   = container.Resolve <IAuthRepository>();
                    var manageRole = authRepo as IManageRoles;
                    var roles      = manageRole.GetRoles(session.UserAuthId);

                    Console.WriteLine($"       Username: {session.UserName}, Roles: {roles.ToSafeJson()}");
                }

                Console.WriteLine($"       {req.Verb}, {req.OperationName}, {req.Dto.ToSafeJson()}");
                Console.WriteLine();

                Console.WriteLine($"<===== Response at [{endTimestamp}]");
                Console.WriteLine($"       Type: {respDto.GetType().Name}");
                // Console.WriteLine($"***** resp: {resp.ToSafeJson()}");
                // Console.WriteLine();

                if (respDto is HttpError)
                {
                    var error      = respDto as HttpError;
                    var respStatus = error.ResponseStatus;
                    Console.WriteLine($"       Status: {error.Status}, {error.StatusCode}, {respStatus.ErrorCode}, {respStatus.Message}");
                    Console.WriteLine();
                }
                else
                {
                    object success = respDto is HttpResult
                    ? (respDto as HttpResult).Response
                    : respDto;
                    Console.WriteLine($"       respDto: {success.ToSafeJson()}");
                    Console.WriteLine();
                }
            });

            //Handle Exceptions occurring in Services:
            //
            ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                //log your exceptions here...
                return(null); //continue with default Error Handling

                //or return your own custom response
                //return DtoUtils.CreateErrorResponse(request, exception);
            });

            //Handle Unhandled Exceptions occurring outside of Services
            //E.g. Exceptions during Request binding or in filters:
            //
            UncaughtExceptionHandlers.Add((req, res, operationName, ex) => {
                res.Write($"Error: {ex.GetType().Name}: {ex.Message}");
                res.EndRequest(skipHeaders: true);
            });

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = true,
            });
            container.Resolve <IAuthRepository>().InitSchema();

            // // TODO: Replace OAuth App settings in: appsettings.Development.json
            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[] {
                // new NetCoreIdentityAuthProvider(AppSettings) { // Adapter to enable ServiceStack Auth in MVC
                //     AdminRoles = { "Manager" }, // Automatically Assign additional roles to Admin Users
                // },
                new BasicAuthProvider(),                  //Allow Sign-ins with HTTP Basic Auth
                new CredentialsAuthProvider(AppSettings), // Sign In with Username / Password credentials
                // new FacebookAuthProvider(AppSettings), /* Create Facebook App at: https://developers.facebook.com/apps */
                // new TwitterAuthProvider(AppSettings),  /* Create Twitter App at: https://dev.twitter.com/apps */
                // new GoogleAuthProvider(AppSettings),   /* Create App https://console.developers.google.com/apis/credentials */
                // new MicrosoftGraphAuthProvider(AppSettings),   /* Create App https://apps.dev.microsoft.com */
            })
            {
                IncludeRegistrationService = true,
                IncludeAssignRoleServices  = false,
            });

            AddSeedUsers((IUserAuthRepository)container.Resolve <IAuthRepository>());
        }