public override void Configure(Funq.Container container) { const Feature disableFeatures = Feature.Jsv | Feature.Soap; SetConfig(new EndpointHostConfig { EnableFeatures = Feature.All.Remove(disableFeatures), DebugMode = true, GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, } }); container.Register<IResourceManager>(new ConfigurationResourceManager()); container.Register<IValidator<Todo>>(new TodoValidator()); container.Register(c => new Config(c.Resolve<IResourceManager>())); var appConfig = container.Resolve<Config>(); container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(appConfig.ConnectionString, SqlServerOrmLiteDialectProvider.Instance)); ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>()); Routes .Add<Todos>("/todos") .Add<Todos>("/todos/{Id}"); log.InfoFormat("AppHost Configured: " + DateTime.Now); }
public static void AddDummyUserIfRequired(Funq.Container container) { // create a dummy user var fac = container.Resolve<IDbConnectionFactory> (); using (var db = fac.OpenDbConnection ()) { if (db.FirstOrDefault<DBUser> (u => u.Username == "dummy") == null) { var user = new DBUser (); user.Username = "******"; user.CreateCryptoFields ("foobar123"); user.FirstName = "John Dummy"; user.LastName = "Doe"; user.AdditionalData = "Dummy user that is created when in development mode"; user.IsActivated = true; user.IsVerified = true; user.Manifest.LastSyncRevision = 0; user.EmailAddress = "*****@*****.**"; db.Insert<DBUser> (user); // insert some sample notes var f = container.Resolve<IDbStorageFactory> (); var key = user.GetPlaintextMasterKey ("foobar123"); var r = new RequestingUser { Username = "******", EncryptionMasterKey = key.ToHexString () }; using (var storage = f.GetDbStorage (r)) { var sample_notes = new DiskStorage (); sample_notes.SetPath ("../../../sample_notes/"); sample_notes.CopyTo (storage); } } } }
/// <summary> /// The configure container. /// </summary> /// <param name="container"> /// The container. /// </param> public override void ConfigureContainer(Funq.Container container) { container.Register<ISearcher>(ExamineManager.Instance.SearchProviderCollection["GravyframeNewsSearcher"]); container.Register<INodeFactoryFacade>(new NodeFactoryFacade()); container.Register<INewsConfiguration>( new NewsConfiguration(container.Resolve<INodeFactoryFacade>(), 1069)); container.Register<NewsDao<UmbracoNews>>( new NewsDao( container.Resolve<INewsConfiguration>(), container.Resolve<INodeFactoryFacade>(), container.Resolve<ISearcher>())); container.Register<IResponseHydrogenationTaskList<NewsRequest, NewsResponse<UmbracoNews>>>( new NewsResponseHydrogenationTaskList(container)); }
public override void Configure(Funq.Container container) { //Resource manager container.Register<IResourceManager>(new ConfigurationResourceManager()); var appSettings = container.Resolve<IResourceManager>(); Plugins.Add(new SessionFeature()); string redis = appSettings.GetString("redis_connection_string"); container.Register<IRedisClientsManager>(c => new BasicRedisClientManager(redis)); // Register storage for user sessions container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient()).ReusedWithin(Funq.ReuseScope.None); container.Register<ISessionFactory>(c => new SessionFactory(c.Resolve<ICacheClient>())); // Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; // Validation Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(Namespace_ApiProject).Assembly); Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new FbOAuth2Provider(appSettings), new VkOAuth2Provider(appSettings), })); //container.Register<ICacheClient>(new MemoryCacheClient()); Plugins.Add(new ServiceStack.Api.Swagger.SwaggerFeature()); container.Adapter = new StructureMapContainerAdapter(); }
public override void Configure(Funq.Container container) { container.Register<IDbConnectionFactory>( c => new OrmLiteConnectionFactory("~/App_Data/db.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); container.RegisterAutoWired<JournalService>(); container.RegisterAutoWired<SessionService>(); using (var db = container.Resolve<IDbConnectionFactory>().Open()) { db.DropAndCreateTable<Journal>(); db.DropAndCreateTable<Session>(); db.DropAndCreateTable<Task>(); db.DropAndCreateTable<JournalNote>(); db.DropAndCreateTable<SessionNote>(); //Seed Lists db.InsertAll(SeedData.JournalSeed); db.InsertAll(SeedData.JournalNoteSeed); db.InsertAll(SeedData.SessionSeed); db.InsertAll(SeedData.TaskSeed); db.InsertAll(SeedData.SessionNoteSeed); } }
/* Uncomment to enable ServiceStack Authentication and CustomUserSession */ private void ConfigureAuth(Funq.Container container) { var appSettings = new AppSettings(); //Default route: /auth/{provider} Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new AcmeCredentialsAuthProvider(appSettings), })); //Default route: /register Plugins.Add(new RegistrationFeature()); //Requires ConnectionString configured in Web.Config var connectionString = ConfigurationManager.ConnectionStrings["SSHelloWorldAuth"].ConnectionString; container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider)); container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); authRepo.CreateMissingTables(); // CreateUser(authRepo, 1, "testuser", null, "Test2#4%"); }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); var appSettings = new AppSettings(); var connString = appSettings.Get("SQLSERVER_CONNECTION_STRING", ConfigUtils.GetConnectionString("UserAuth")); container.Register<IDbConnectionFactory>( new OrmLiteConnectionFactory(connString, SqlServerDialect.Provider)); //Using an in-memory cache container.Register<ICacheClient>(new MemoryCacheClient()); ConfigureAuth(container); var dbFactory = container.Resolve<IDbConnectionFactory>(); dbFactory.Run(d => d.CreateTableIfNotExists<UserAuth>()); dbFactory.Run(db => db.CreateTableIfNotExists<Message>()); dbFactory.Run(d => d.CreateTableIfNotExists<Device>()); SetConfig(new EndpointHostConfig { DefaultContentType = ContentType.Json, EnableFeatures = Feature.All.Remove(Feature.Html).Remove(Feature.Xml), AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Json } }); //Or if Haz Redis //container.Register<ICacheClient>(new PooledRedisClientManager()); }
public override void Configure(Funq.Container container) { Routes .Add<Hello>("/hello") .Add<Hello>("/hello/{Name}"); helloService = container.Resolve<HelloService>(); AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {new BasicAuthProvider(), new TwitterAuthProvider(new AppSettings()),}); //authFeature.HtmlRedirect Plugins.Add(authFeature); MemoryCacheClient memoryCacheClient = new MemoryCacheClient(); container.Register<ICacheClient>(memoryCacheClient); var userRepository = new InMemoryAuthRepository(); container.Register<IUserAuthRepository>(userRepository); string hash; string salt; string password = "******"; new SaltedHash().GetHashAndSaltString(password, out hash, out salt); userRepository.CreateUserAuth( new UserAuth { Id = 1, DisplayName = "JoeUser", Email = "*****@*****.**", UserName = "******", FirstName = "Joe", LastName = "User", PasswordHash = hash, Salt = salt, }, password); //IHttpResult authenticationRequired = helloService.AuthenticationRequired(); // ???? }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; container.Register<ICacheClient>(new MemoryCacheClient()); container.Register<IDbConnectionFactory>( new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["Db"].ToString(), SqlServerDialect.Provider)); Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(MeetingValidator).Assembly); //https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#userauth-persistence---the-iuserauthrepository //Use ServiceStacks authentication/authorization persistence var userRep = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>()); container.Register<IUserAuthRepository>(userRep); userRep.CreateMissingTables(); //Create missing Auth var appSettings = new AppSettings(); Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(), new GoogleOpenIdOAuthProvider(appSettings), })); Plugins.Add(new RegistrationFeature()); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); }
/* Example ServiceStack Authentication and CustomUserSession */ private void ConfigureAuth(Funq.Container container) { var appSettings = new AppSettings(); //Default route: /auth/{provider} Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(appSettings), new FacebookAuthProvider(appSettings), new TwitterAuthProvider(appSettings), new BasicAuthProvider(appSettings), })); //Default route: /register Plugins.Add(new RegistrationFeature()); //Requires ConnectionString configured in Web.Config var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString; container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider)); container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); container.Resolve<IUserAuthRepository>().InitSchema(); }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; var connectionString = ConfigurationManager.ConnectionStrings["conString"].ToString(); Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider)); var appSettings = new AppSettings(); Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(), new FacebookAuthProvider(appSettings), new GoogleOpenIdOAuthProvider(appSettings), })); Plugins.Add(new RegistrationFeature()); var userRep = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>()); container.Register<IUserAuthRepository>(userRep); var redisCon = ConfigurationManager.AppSettings["redisUrl"].ToString(); container.Register<IRedisClientsManager>(new PooledRedisClientManager(20, 60, redisCon)); container.Register<ICacheClient>(c => (ICacheClient)c.Resolve<IRedisClientsManager>().GetCacheClient()); userRep.CreateMissingTables(); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); }
public void CreateMissingTables(Funq.Container container) { using (IDbConnection db = dbConnectionFactory.OpenDbConnection()) { ((OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>()).CreateMissingTables(); db.CreateTableIfNotExists<CategoryModels>(); db.CreateTableIfNotExists<BookModels>(); db.CreateTableIfNotExists<BookPropertyModels>(); } }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //Configure User Defined REST Paths //Routes // .Add<Hello>("/hello") // .Add<Hello>("/hello/{Name*}") //.Add<Events>("/Events/") //.Add<Events>("/Events/{Lag*}"); //Uncomment to change the default ServiceStack configuration //SetConfig(new EndpointHostConfig { //}); //Enable Authentication //ConfigureAuth(container); var appSettings = new AppSettings(); string baseApiUrl = appSettings.Get("BaseApiUrl","foo"); //Register all your dependencies // container.Register<IJellybeanDispenser>(c => new VanillaJellybeanDispenser()); // container.Register(c => new SweetVendingMachine(c.Resolve<IJellybeanDispenser>())); // container.Register(c => new SweetShop(c.Resolve<SweetVendingMachine>())); // See more at: http://anthonysteele.co.uk/the-funq-ioc-container#sthash.ketDSF72.dpuf container.Register<IAppConfig>(c=>new AppConfig()); container.Register<IEventRepository>(c=> new EventRepository()); container.Resolve<IEventRepository>().Config = container.Resolve<IAppConfig>(); // container.Register(c => new TodoRepository()); //Register a external dependency-free container.Register<ICacheClient>(new MemoryCacheClient()); //Configure an alt. distributed persistent cache that survives AppDomain restarts. e.g Redis //container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379")); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); }
/// <summary> /// Configures the application host. /// </summary> /// <param name="container">The container.</param> public override void Configure(Funq.Container container) { // Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; // Create the connection factory for our database. var factory = new OrmLiteConnectionFactory(WebConfigurationManager.ConnectionStrings["SquarePeg"].ConnectionString, MySqlDialect.Provider); // Register database. container.Register(c => factory.OpenDbConnection()); // Register logging. container.Register<ILog>(c => LogManager.GetLogger(this.GetType())); // Register caching dependencies. container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379")); container.Register<ICacheClient>(c => (ICacheClient)c.Resolve<IRedisClientsManager>() .GetCacheClient()) .ReusedWithin(Funq.ReuseScope.None); // Register repositories container.Register<IBoardsRepository>(c => new BoardsRepository(container.Resolve<IDbConnection>())); // Register services. container.Register<IBoardsService>( c => new BoardsService(container.Resolve<IBoardsRepository>(), container.Resolve<ICacheClient>())); // Configure the authentiation. this.ConfigureAuth(container, factory); // Set the sharec container; this is used by other shared omponents such as aspects. SharedContainer.Container = container; // Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties JsConfig.EmitCamelCaseNames = true; //Register Typed Config some services might need to access var appConfig = new AppConfig(new AppSettings()); //appconfig will contain properties from web.config container.Register(appConfig); //inform api that this will be using BasicAuth to authenticate/authorize users Plugins.Add(new AuthFeature( () => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(), })); //add registration functionality (user will need admin role to access this) Plugins.Add(new RegistrationFeature()); //add validation using fluent validation package Plugins.Add(new ValidationFeature()); //register service to validate container.RegisterValidators(typeof(AwardService).Assembly); if (appConfig.UseRedis){ //setup cache client to user redis container.Register<IRedisClientsManager>(c => new PooledRedisClientManager(appConfig.RedisReadWriteHosts.ToArray())); container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient()); //setup redis for authentication repository container.Register<IUserAuthRepository>(c => new RedisAuthRepository(c.Resolve<IRedisClientsManager>())); } else { //setup cache client to be InMemory container.Register<ICacheClient>(c => new MemoryCacheClient()); //setup authentication repository to be InMemory container.Register<IUserAuthRepository>(c => new InMemoryAuthRepository()); } //seed possible users SeedUsers(container.Resolve<IUserAuthRepository>()); //register any repository classes here container.RegisterAutoWired<AwardRepository>(); }
public override void Configure(Funq.Container container) { container.Register<IAuthProvider>((c) => new AuthProvider()); Routes .Add<GetDataRequest>("/GetData"); this.RequestFilters.Add((req, res, dto) => { //if (!req.IsSecureConnection) //{ // res.StatusCode = 401; // res.Close(); //} if (req.Headers["Authorization"] != null) { const string key = "Bearer "; string accessToken = null; var header = req.Headers["Authorization"]; if (header.StartsWith(key)) { accessToken = header.Substring(key.Length); } if (string.IsNullOrWhiteSpace(accessToken)) { res.StatusCode = 401; res.Close(); } //Lookup var provider = container.Resolve<IAuthProvider>(); if (!provider.UserIsValid(accessToken)) { res.StatusCode = 401; res.Close(); } } }); }
public override void Configure(Funq.Container container) { //SwaggerUI配置用于调试 AddPlugin(new SwaggerFeature()); //IOC配置 ServiceLocatorConfig.Configura(container); //rabbitmq配置 var mq = new RabbitMqServer(ConfigurationManager.AppSettings.Get("EventProcessorAddress")) { AutoReconnect = true, DisablePriorityQueues = true, RetryCount = 0 }; container.Register<IMessageService>(c => mq); var mqServer = container.Resolve<IMessageService>(); //注册eventHandler mq.RegisterHandler<BuildOrderReady>(ServiceController.ExecuteMessage, 1); mq.RegisterHandler<PaySuccessReady>(ServiceController.ExecuteMessage, 1); mqServer.Start(); }
public static void ConfigureAuth(List<IPlugin> Plugins, Funq.Container container) { //Enable and register existing services you want this host to make use of. //Look in Web.config for examples on how to configure your oauth proviers, e.g. oauth.facebook.AppId, etc. var appSettings = new AppSettings(); //Register all Authentication methods you want to enable for this web app. Plugins.Add(new AuthFeature( () => new AuthUserSession(), //Use your own typed Custom UserSession type new IAuthProvider[] { new CredentialsAuthProvider() })); //Provide service for new users to register so they can login with supplied credentials. Plugins.Add(new RegistrationFeature()); //Create a DB Factory configured to access the UserAuth SQL Server DB var connStr = appSettings.Get("MYSQL_CONNECTION_STRING", //AppHarbor or Local connection string ConfigUtils.GetConnectionString("UserAuth")); container.Register<IDbConnectionFactory>( new OrmLiteConnectionFactory(connStr, //ConnectionString in Web.Config ServiceStack.OrmLite.MySql.MySqlDialectProvider.Instance) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); //Store User Data into the referenced SqlServer database container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); //If using and RDBMS to persist UserAuth, we must create required tables if (appSettings.Get("RecreateAuthTables", false)) authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables else authRepo.CreateMissingTables(); //Create only the missing tables }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //Register Typed Config some services might need to access var appSettings = new AppSettings(); Config = new AppConfig(appSettings); container.Register(Config); //Register all your dependencies: //Register a external dependency-free container.Register<ICacheClient>(new MemoryCacheClient()); //Configure an alt. distributed peristed cache that survives AppDomain restarts. e.g Redis //container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379")); //Enable Authentication an Registration ConfigureAuth(container); //Create you're own custom User table var dbFactory = container.Resolve<IDbConnectionFactory>(); dbFactory.Exec(dbCmd => dbCmd.CreateTable<User>(overwrite: true)); //Register application services container.Register(new TodoRepository()); container.Register<ITwitterGateway>(new TwitterGateway()); //Configure Custom User Defined REST Paths for your services ConfigureServiceRoutes(); //Change the default ServiceStack configuration //const Feature disableFeatures = Feature.Jsv | Feature.Soap; SetConfig(new EndpointHostConfig { //EnableFeatures = Feature.All.Remove(disableFeatures), AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Html }, DebugMode = true, //Show StackTraces in service responses during development }); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); ServiceStackController.CatchAllController = reqCtx => container.TryResolve<HomeController>(); }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //Load environment config from text file if exists var liveSettings = "~/appsettings.txt".MapHostAbsolutePath(); var appSettings = File.Exists(liveSettings) ? (IAppSettings)new TextFileSettings(liveSettings) : new AppSettings(); AppConfig = new AppConfig(appSettings); container.Register(AppConfig); //Change the default ServiceStack configuration //const Feature disableFeatures = Feature.Jsv | Feature.Soap; SetConfig(new HostConfig { AppendUtf8CharsetOnContentTypes = new HashSet<string> { MimeTypes.Html }, HandlerFactoryPath = "api", DebugMode = true, }); //Register a external dependency-free container.Register<ICacheClient>(new MemoryCacheClient()); //Configure an alt. distributed persistent cache that survives AppDomain restarts. e.g Redis //container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379")); //Enable Authentication an Registration ConfigureAuth(container, appSettings); //Create your own custom User table using (var db = container.Resolve<IDbConnectionFactory>().Open()) db.DropAndCreateTable<User>(); //Register application services container.Register(new TodoRepository()); container.Register<ITwitterGateway>(new TwitterGateway()); //Configure Custom User Defined REST Paths for your services ConfigureServiceRoutes(); Plugins.Add(new SwaggerFeature { UseBootstrapTheme = true }); Plugins.Add(new PostmanFeature()); Plugins.Add(new CorsFeature()); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); ServiceStackController.CatchAllController = reqCtx => container.TryResolve<HomeController>(); }
private void ConfigureAuth(Funq.Container container, IAppSettings appSettings) { //Enable and register existing services you want this host to make use of. //Look in Web.config for examples on how to configure your oauth providers, e.g. oauth.facebook.AppId, etc. //Register all Authentication methods you want to enable for this web app. Plugins.Add(new AuthFeature( () => new CustomUserSession(), //Use your own typed Custom UserSession type new IAuthProvider[] { new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials new TwitterAuthProvider(appSettings), //Sign-in with Twitter new FacebookAuthProvider(appSettings), //Sign-in with Facebook new DigestAuthProvider(appSettings), //Sign-in with Digest Auth new BasicAuthProvider(), //Sign-in with Basic Auth new YahooOpenIdOAuthProvider(appSettings), //Sign-in with Yahoo OpenId new OpenIdOAuthProvider(appSettings), //Sign-in with Custom OpenId })); //Provide service for new users to register so they can login with supplied credentials. Plugins.Add(new RegistrationFeature()); //override the default registration validation with your own custom implementation container.RegisterAs<CustomRegistrationValidator, IValidator<Register>>(); //Create a DB Factory configured to access the UserAuth PostgreSQL DB var connStr = appSettings.GetString("ConnectionString"); container.Register<IDbConnectionFactory>( new OrmLiteConnectionFactory(connStr, //ConnectionString in Web.Config PostgreSqlDialect.Provider) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); //Store User Data into the referenced SqlServer database container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); //If using and RDBMS to persist UserAuth, we must create required tables if (appSettings.Get("RecreateAuthTables", false)) authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables else authRepo.InitSchema(); //Create only the missing tables Plugins.Add(new RequestLogsFeature()); }
//Configure ServiceStack Authentication and CustomUserSession private void ConfigureAuth(Funq.Container container) { Routes .Add<Register>("/register"); var appSettings = new AppSettings(); Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(appSettings), new FacebookAuthProvider(appSettings), new TwitterAuthProvider(appSettings), new GoogleOpenIdOAuthProvider(appSettings), new OpenIdOAuthProvider(appSettings), new DigestAuthProvider(appSettings), new BasicAuthProvider(appSettings), })); Plugins.Add(new RegistrationFeature()); container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); var authRepo = (OrmLiteAuthRepository)container.Resolve<IAuthRepository>(); if (new AppSettings().Get("RecreateTables", true)) authRepo.DropAndReCreateTables(); else authRepo.InitSchema(); }
// Uncomment to enable ServiceStack Authentication and CustomUserSession private void ConfigureAuth(Funq.Container container) { var appSettings = new AppSettings(); //Default route: /auth/{provider} Plugins.Add(new AuthFeature(() => new CustomUserSession(), //Use your own typed Custom UserSession type new IAuthProvider[] { //new CredentialsAuthProvider(appSettings), new CustomCredentialsAuthProvider(appSettings), new FacebookAuthProvider(appSettings), //new TwitterAuthProvider(appSettings), new BasicAuthProvider(appSettings), })); //Default route: /register Plugins.Add(new RegistrationFeature()); //override the default registration validation with your own custom implementation container.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>(); ////Requires ConnectionString configured in Web.Config //var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString; //container.Register<IDbConnectionFactory>(c => // new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider)); container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); authRepo.ValidUserNameRegEx = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); authRepo.CreateMissingTables(); }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //Configure User Defined REST Paths //Routes // .Add<Hello>("/hello") // .Add<Hello>("/hello/{Name*}"); //Uncomment to change the default ServiceStack configuration //SetConfig(new EndpointHostConfig { //}); //Enable Authentication //ConfigureAuth(container); //Register all your dependencies //container.Register(new TodoRepository()); container.Register(new WorkersRepository()); container.Register(new IdentifyRepository()); container.Register(new ResultRepository()); container.Register(new SimAppScreenRepository()); //TODO test - is it ok to upload from DB here - or from instance creation var myrepository = container.Resolve<SimAppScreenRepository>(); myrepository.UploadFromDB(); container.Register(new GraphicRepository()); var mygrrepository = container.Resolve<GraphicRepository>(); mygrrepository.UploadFromDB(); SetConfig(new HostConfig { DefaultRedirectPath = "/WebApp/GenericUI.html" }); //Set once before use (i.e. in a static constructor). OrmLiteConfig.DialectProvider = SqlServerDialect.Provider; //SqlServerDialect.Provider. //OrmLiteConfig.DialectProvider.DefaultStringLength = using (IDbConnection db = "Data Source=localhost;Initial Catalog=restmasterservice;Integrated Security=True".OpenDbConnection()) { db.CreateTable<ResultDTO>(false); //db.Insert(new IdentifyDTO()ple { Id = 1, Name = "Hello, World!" }); //var rows = db.Select<SimpleExample>(); //Assert.That(rows, Has.Count(1)); //Assert.That(rows[0].Id, Is.EqualTo(1)); } }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //Configure User Defined REST Paths //Routes // .Add<Hello>("/hello") // .Add<Hello>("/hello/{Name*}"); //Uncomment to change the default ServiceStack configuration //SetConfig(new EndpointHostConfig { //}); //Register Typed Config some services might need to access var appSettings = new AppSettings(); AppConfig = new AppConfig(appSettings); container.Register(AppConfig); //Register all your dependencies //container.Register(new TodoRepository()); container.Register<ICacheClient>(new MemoryCacheClient()); // Register DB container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory( "~/App_Data/db.sqlite".MapHostAbsolutePath(), SqliteOrmLiteDialectProvider.Instance)); // Reset DB using (var resetDb = container.Resolve<ResetDbService>()) { resetDb.Any(null); } //Enable Authentication ConfigureAuth(container); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); ServiceStackController.CatchAllController = reqCtx => container.TryResolve<HomeController>(); }
/// <summary> /// The Configure method of the HelloAppHost is the central IoC container location. /// All configured services, plugins and resources are centrally managed from here. /// </summary> /// <param name="container"></param> public override void Configure(Funq.Container container) { string soon = DateTime.Now.AddSeconds(10).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"); SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, { "Access-Control-Allow-Headers", "Content-Type" }, { "Cache-Control", "no-cache, no-store, must-revalidate"}, { "Pragma", "no-cache"}, { "Expires", "0"}, { "X-Powered-On", Environment.MachineName} }, DefaultContentType = "application/json" }); // Auto Add all Routes Routes.AddFromAssembly(typeof(Person).Assembly); // Fluent Validation Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(Person).Assembly); // Database Connection ConnectionStringSettingsCollection css = ConfigurationManager.ConnectionStrings; string cs = css["storage"].ConnectionString; container.Register<IDbConnectionFactory>(c => new OrmLiteConnectionFactory(cs, MySqlDialectProvider.Instance)); var loadStore = container.Resolve<StorageService>(); loadStore.Get(null); }
public override void Configure(Funq.Container container) { //to inject third-party IoC (for example for NInject use SrviceStack.ContainerAdapter.NInject) //IKernel kernel=new StandartKernel(); //kernel.Bind<TrackedDataRepository>().ToSelf(); //container.Adapter=new NinjectContainerAdapter(kernel); -> provide a adapter layer for NInject to use in Funq Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider() , new TwitterAuthProvider(new AppSettings())})); Plugins.Add(new RegistrationFeature()); //register validators Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(Common.Entry).Assembly, typeof(EntryService).Assembly); //request logs Plugins.Add(new RequestLogsFeature()); // added ability to view request via http:/..../requestlogs //cache registration container.Register<ICacheClient>(new MemoryCacheClient()); container.Register<IRedisClientsManager>(new PooledRedisClientManager("localhost:6379")); //container.Register<ICacheClient>(r => (ICacheClient)r.Resolve<IRedisClientsManager>().GetCacheClient()); var userRepository = new InMemoryAuthRepository(); container.Register<IUserAuthRepository>(userRepository); string hash; string salt; new SaltedHash().GetHashAndSaltString("password1", out hash, out salt); userRepository.CreateUserAuth(new UserAuth() { Id = 1, DisplayName = "Joe user", Email = "*****@*****.**", UserName = "******", LastName = "jname", PasswordHash = hash, Salt = salt, Roles = new List<string> { RoleNames.Admin }//, //Permissions = new List<string> { "GetStatus", "AddStatus" } }, "password1"); //automatically inject in all public properties container.RegisterAutoWired<TrackedDataRepository>().ReusedWithin(Funq.ReuseScope.Default); container.RegisterAutoWired<TrackedDataRepository2>().ReusedWithin(Funq.ReuseScope.Default); var dbConFactory = new OrmLiteConnectionFactory(HttpContext.Current.Server.MapPath("~/App_Data/data.txt"), SqliteDialect.Provider) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }; container.Register<IDbConnectionFactory>(dbConFactory); SetConfig(new EndpointHostConfig { DebugMode = true }); var mqService = new RedisMqServer(container.Resolve<IRedisClientsManager>()); mqService.RegisterHandler<Entry>(ServiceController.ExecuteMessage); mqService.Start(); //install Razor Plugins.Add(new RazorFormat()); }
// This is the "Composition Root" in the IoC pattern that wires all // our objects/implementations up, based on a given configuration. // config sanity checks SHOULD NOT go here private static void ComposeObjectGraph(Funq.Container container) { var config = Config.Global; container.Register<SqliteConfig> (c => new SqliteConfig { File = Path.Combine (config.DataPath, "rainy.db") }); container.Register<PostgreConfig> (c => { dynamic txt_conf = config.Postgre; var psql_conf = new PostgreConfig (); if (!string.IsNullOrEmpty (txt_conf.Username)) psql_conf.Username = txt_conf.Username; if (!string.IsNullOrEmpty (txt_conf.Password)) psql_conf.Password = txt_conf.Password; if (!string.IsNullOrEmpty (txt_conf.Database)) psql_conf.Database = txt_conf.Database; if (!string.IsNullOrEmpty (txt_conf.Host)) psql_conf.Host = txt_conf.Host; if (txt_conf.Port > 0) psql_conf.Port = (uint) txt_conf.Port; return psql_conf; }); if (config.Backend == "xml") { // use username/password pairs from the config file container.Register<IAuthenticator> (c => { return new ConfigFileAuthenticator(config.User); }); // we store notes in XML files in the DataPath container.Register<IDataBackend> (c => { var auth = c.Resolve<IAuthenticator> (); var factory = c.Resolve<IDbConnectionFactory> (); var oauth_handler = c.Resolve<OAuthHandler> (); return new FileSystemBackend (config.DataPath, factory, auth, oauth_handler, false); }); } else { // database based backends switch ((string) config.Backend) { case "sqlite": container.Register<IDbConnectionFactory> (c => { var conf = container.Resolve<SqliteConfig> (); var connection_string = conf.ConnectionString; var factory = new OrmLiteConnectionFactory (connection_string, SqliteDialect.Provider); if (!File.Exists (conf.File)) { DatabaseBackend.CreateSchema (factory); } return (IDbConnectionFactory) factory; }); break; case "postgre": container.Register<IDbConnectionFactory> (c => { var connection_string = container.Resolve<PostgreConfig> ().ConnectionString; var factory = new OrmLiteConnectionFactory (connection_string, PostgreSqlDialect.Provider); DatabaseBackend.CreateSchema (factory); return factory; }); break; } container.Register<IAuthenticator> (c => { var factory = c.Resolve<IDbConnectionFactory> (); // var sfactory = new OrmLiteConnectionFactory (); var dbauth = new DbAuthenticator (factory); //var dbauth = new ConfigFileAuthenticator (Config.Global.Users); // we have to make sure users from the config file exist with the configured password // in the db // TODO delete old users? or restrict to webinterface? if (dbauth is ConfigFileAuthenticator) { foreach (dynamic user in Config.Global.Users) { string username = user.Username; string password = user.Password; using (var db = factory.OpenDbConnection ()) { var db_user = db.FirstOrDefault<DBUser> (u => u.Username == username); if (db_user != null) { var need_update = db_user.UpdatePassword (password); if (need_update) db.UpdateOnly (new DBUser { PasswordHash = db_user.PasswordHash }, u => new { u.PasswordHash }, (DBUser p) => p.Username == username); } else { // create the user in the db var new_user = new DBUser (); new_user.Username = username; new_user.CreateCryptoFields (password); new_user.UpdatePassword (password); db.Insert<DBUser> (new_user); } } } } return dbauth; }); // container.Register<IAdminAuthenticator> (c => { var auth = new ConfigFileAdminAuthenticator (); return auth; }); container.Register<OAuthHandler> (c => { var auth = c.Resolve<IAuthenticator> (); var factory = c.Resolve<IDbConnectionFactory> (); // ITokenRepository<AccessToken> access_tokens = new SimpleTokenRepository<AccessToken> (); // ITokenRepository<RequestToken> request_tokens = new SimpleTokenRepository<RequestToken> (); ITokenRepository<AccessToken> access_tokens = new DbAccessTokenRepository<AccessToken> (factory); ITokenRepository<RequestToken> request_tokens = new DbRequestTokenRepository<RequestToken> (factory); ITokenStore token_store = new RainyTokenStore (access_tokens, request_tokens); OAuthHandler handler = new OAuthHandler (auth, access_tokens, request_tokens, token_store); return handler; }); container.Register<DbStorageFactory> (c => { var conn_factory = c.Resolve<IDbConnectionFactory> (); bool use_encryption = (bool) Config.Global.UseNoteEncryption; var storage_factory = new DbStorageFactory (conn_factory, use_encryption, use_history: true); return storage_factory; }); container.Register<IDataBackend> (c => { var conn_factory = c.Resolve<IDbConnectionFactory> (); var storage_factory = c.Resolve<DbStorageFactory> (); var handler = c.Resolve<OAuthHandler> (); var auth = c.Resolve<IAuthenticator> (); return new DatabaseBackend (conn_factory, storage_factory, auth, handler); }); /* container.Register<OAuthHandler> (c => { var factory = c.Resolve<IDbConnectionFactory> (); var access_token_repo = new DbAccessTokenRepository<AccessToken> (factory); var request_token_repo = new SimpleTokenRepository<RequestToken> (); var auth = c.Resolve<IAuthenticator> (); var token_store = new Rainy.OAuth.SimpleStore.SimpleTokenStore (access_token_repo, request_token_repo); var handler = new OAuthHandler (auth, token_store); return handler; }); */ AddDummyUserIfRequired (container); } }
public override void Configure(Funq.Container container) { //Set JSON web services to return idiomatic JSON camelCase properties ServiceStack.Text.JsConfig.EmitCamelCaseNames = true; //https://github.com/wordnik/swagger-core/wiki //Document your code and expose it to the world Plugins.Add(new SwaggerFeature()); //Registers authorization service and endpoints /auth and /auth{provider} Plugins.Add(new AuthFeature( () => new AuthUserSession(), new IAuthProvider[] { new CredentialsAuthProvider() } ) {HtmlRedirect = null}); //Registers registartion service and endpoints /register, /assignroles, /unassignroles Plugins.Add(new RegistrationFeature()); this.RegisterAs<MyRegistrationValidator, IValidator<Registration>>(); Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(CreateOrderValidator).Assembly); var dataFilePath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "\\data.db"; container.Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(dataFilePath, SqliteDialect.Provider)); var userRep = new OrmLiteAuthRepository(container.Resolve<IDbConnectionFactory>()); container.Register<IUserAuthRepository>(userRep); var redisCon = ConfigurationManager.AppSettings["redisUrl"].ToString(); container.Register<IRedisClientsManager>(new PooledRedisClientManager(20, 60, redisCon)); container.Register<ICacheClient>(c =>(ICacheClient)c.Resolve<IRedisClientsManager>().GetCacheClient()); //Set MVC to use the same Funq IOC as ServiceStack ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container)); //https://github.com/ServiceStack/ServiceStack.Redis/wiki/RedisPubSub //start threads that subscribe to Redis channels for Pub/Sub new OrderSubscribers(container).StartSubscriberThreads(); new FulfillmentSubscribers(container).StartSubscriberThreads(); //https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#userauth-persistence---the-iuserauthrepository //Use ServiceStacks authentication/authorization persistence userRep.CreateMissingTables(); //Create missing Auth //Re-Create Tables for the demo using (var con = AppHostBase.Resolve<IDbConnectionFactory>().OpenDbConnection()) { con.CreateTable<Order>(true); con.CreateTable<Fulfillment>(true); } //clear redis using (var redis = AppHostBase.Resolve<IRedisClientsManager>().GetClient()) { } //Create dummy user accounts (TestUser/Password) foreach(var user in DummyUserAccounts.GetDummyAccounts()) { if(userRep.GetUserAuthByUserName(user.UserName) == null) userRep.CreateUserAuth(new UserAuth {UserName = user.UserName}, user.Password); } }
//Configure ServiceStack Authentication and CustomUserSession private void ConfigureAuth(Funq.Container container) { Routes .Add<Auth>("/auth") .Add<Auth>("/auth/{provider}") .Add<Registration>("/register"); var appSettings = new AppSettings(); AuthFeature.Init(this, () => new CustomUserSession(), new IAuthProvider[] { new CredentialsAuthProvider(appSettings), new FacebookAuthProvider(appSettings), new TwitterAuthProvider(appSettings), new BasicAuthProvider(appSettings), }); RegistrationFeature.Init(this); container.Register<IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>())); var authRepo = (OrmLiteAuthRepository)container.Resolve<IUserAuthRepository>(); if (new AppSettings().Get("Recr eateTables", true)) authRepo.DropAndReCreateTables(); else authRepo.CreateMissingTables(); }