Example #1
0
 /// <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)
 {
     Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CustomAuthentication(), }));
     container.Register<ICacheClient>(new MemoryCacheClient());
     var userRepository = new InMemoryAuthRepository();
     container.Register<IUserAuthRepository>(userRepository);
 }
Example #2
0
        public override void Configure(Funq.Container container)
        {
            // ASP.NET MVC integration
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));

            SetConfig(CreateEndpointHostConfig());
        }
 public void Install(Container container)
 {
     container.RegisterAutoWired<DbManagementService>();
     container.RegisterAutoWired<ImageCreator>();
     container.RegisterAutoWired<OrderPersister>();
     container.RegisterAutoWired<BagOfCandyPersister>();
 }
        public void Install(Container container)
        {
            var userRepo = new InMemoryAuthRepository();

            container.Register<IUserAuthRepository>(userRepo);

            //HACK: Add default users
            var users = new[]
                {
                    new User("Admin", "AdminPassword"),
                    new User("cyberzed", "cyberzed")
                };

            foreach (var user in users)
            {
                string hash;
                string salt;

                new SaltedHash().GetHashAndSaltString(user.Password, out hash, out salt);

                userRepo.CreateUserAuth(
                    new UserAuth
                        {
                            DisplayName = user.Username,
                            UserName = user.Username,
                            PasswordHash = hash,
                            Salt = salt
                        },
                    user.Password);
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var container = new Container();
            Tepeyac.Funq.Registry.Register(container);

            container.Register<IFiber>("GuiFiber", c => c.Resolve<IFiber>());
            /*
            container.Register<IFiber>("GuiFiber", c =>
            {
                var executor =
                    c.Resolve<IExecutor>() ??
                    new Executor();
                var invoke = new SynchronizeInvoke(new WindowsFormsSynchronizationContext());
                var fiber = new FormFiber(invoke, executor);
                fiber.Start();

                return fiber;
            });
             */

            container.Register<IBurritoDayView>(c =>
                new BurritoDayView(c));

            container.Resolve<IBurritoDayView>();
            Application.Run();
        }
        /// <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)
        {
            LogManager.LogFactory = new DebugLogFactory();

            OracleDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();

            container.Register<IDbConnectionFactory>(new OrmLiteConnectionFactory(ConfigUtils.GetAppSetting("connectionString"), OracleOrmLiteDialectProvider.Instance));

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


            OrmLiteConfig.InsertFilter = (dbCmd, row) =>
            {
                var auditRow = row as IAudit;
                if (auditRow == null) return;
                var now = SystemClock.Instance.Now;
                var milliseconds = now.Ticks / NodaConstants.TicksPerMillisecond;
                auditRow.CreatedDate = auditRow.ModifiedDate = milliseconds;
            };
            OrmLiteConfig.UpdateFilter = (dbCmd, row) =>
            {
                var auditRow = row as IAudit;
                if (auditRow == null) return;
                var now = SystemClock.Instance.Now;
                var milliseconds = now.Ticks / NodaConstants.TicksPerMillisecond;
                auditRow.ModifiedDate = milliseconds;
            };
        }
    /// <summary>
    /// Configure the given container with the
    /// registrations provided by the funqlet.
    /// </summary>
    /// <param name="container">Container to register.</param>
    public override void Configure(Funq.Container container)
    {
        ServiceStack.OrmLite.OrmLiteConfig.CommandTimeout = 60;
        WebEas.Log.WebEasNLogLogger.Application           = "CFE";
        base.Configure(container);

        this.SetConfig(new HostConfig
        {
            WsdlServiceNamespace = "http://schemas.webeas.sk/office/esam/office/1.0",
            SoapServiceName      = "EsamOfficeCfe",
#if DEBUG || DEVELOP || INT || ITP
            DebugMode      = true,
            EnableFeatures = Feature.All.Remove(this.disableFeaturesDebug),
#else
            DebugMode      = false,
            EnableFeatures = Feature.All.Remove(this.disableFeatures),
#endif
            DefaultContentType = MimeTypes.Json,
            AllowJsonpRequests = true
        });

        container.RegisterAutoWiredAs <BdsRepository, IRepositoryBase>("bds").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<DapRepository, IRepositoryBase>("dap").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<DmsRepository, IRepositoryBase>("dms").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<FinRepository, IRepositoryBase>("fin").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<OsaRepository, IRepositoryBase>("osa").ReusedWithin(ReuseScope.Request);
        container.RegisterAutoWiredAs <RegRepository, IRepositoryBase>("reg").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<RzpRepository, IRepositoryBase>("rzp").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<UctRepository, IRepositoryBase>("uct").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<VykRepository, IRepositoryBase>("vyk").ReusedWithin(ReuseScope.Request);
        //container.RegisterAutoWiredAs<MajRepository, IRepositoryBase>("maj").ReusedWithin(ReuseScope.Request);
        container.RegisterAutoWiredAs <CfeRepository, IRepositoryBase>("cfe").ReusedWithin(ReuseScope.Request);
        container.AddScoped <ICfeRepository, CfeRepository>();
    }
Example #8
0
			public override void Configure(Container container)
			{
				Plugins.Add(new AuthFeature(() => new CustomUserSession(),
					new AuthProvider[] {
						new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
						new BasicAuthProvider(), //Sign-in with Basic Auth
					}));

				container.Register<ICacheClient>(new MemoryCacheClient());
				var userRep = new InMemoryAuthRepository();
				container.Register<IUserAuthRepository>(userRep);

				string hash;
				string salt;
				new SaltedHash().GetHashAndSaltString("test1", out hash, out salt);

				userRep.CreateUserAuth(new UserAuth {
					Id = 1,
					DisplayName = "DisplayName",
					Email = "*****@*****.**",
					UserName = "******",
					FirstName = "FirstName",
					LastName = "LastName",
					PasswordHash = hash,
					Salt = salt,
				}, "test1");
			}
Example #9
0
        public override void Configure(Container container)
        {
            JsConfig.EmitCamelCaseNames = true;
            Plugins.Add(new RazorFormat());

            //Comment out 2 lines below to change to use local FileSystem instead of S3
            var s3Client = new AmazonS3Client(AwsConfig.AwsAccessKey, AwsConfig.AwsSecretKey, RegionEndpoint.USEast1);
            VirtualFiles = new S3VirtualPathProvider(s3Client, AwsConfig.S3BucketName, this);

            container.Register<IPocoDynamo>(c => new PocoDynamo(AwsConfig.CreateAmazonDynamoDb()));
            var db = container.Resolve<IPocoDynamo>();
            db.RegisterTable<Todos.Todo>();
            db.RegisterTable<EmailContacts.Email>();
            db.RegisterTable<EmailContacts.Contact>();
            db.InitSchema();

            //AWS Auth
            container.Register<ICacheClient>(new DynamoDbCacheClient(db, initSchema:true));
            container.Register<IAuthRepository>(new DynamoDbAuthRepository(db, initSchema:true));
            Plugins.Add(CreateAuthFeature());

            //EmailContacts
            ConfigureSqsMqServer(container);
            ConfigureEmailer(container);
            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(EmailContacts.CreateContact).Assembly);
        }
 public override void Configure(Container container)
 {
     //var root = new NinjectCompositionRoot();
     var root = new UnityCompositionRoot();
     //var root = new FunqCompositionRoot();
     root.Compose(container);
 }
Example #11
0
            //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();
                }
            }
Example #12
0
        public override void Configure(Container container)
        {
            //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
            base.SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                    {
                        { "Access-Control-Allow-Origin", "*" },
                        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                    },
            });

            container.Register<IResourceManager>(new ConfigurationResourceManager());
            container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));

            var appConfig = container.Resolve<ExampleConfig>();

            container.Register<IDbConnectionFactory>(c =>
                new OrmLiteConnectionFactory(
                    appConfig.ConnectionString.MapHostAbsolutePath(),
                    SqliteOrmLiteDialectProvider.Instance));

            ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());

            //The MemoryCacheClient is a great way to get started with caching; nothing external to setup.
            container.Register<ICacheClient>(c => new MemoryCacheClient());

            //If you give Redis a try, you won't be disappointed. This however requires Redis to be installed.
            //container.Register<ICacheClient>(c => new BasicRedisClientManager());

            log.InfoFormat("AppHost Configured: {0}", DateTime.Now);
        }
Example #13
0
        /// <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)
        {
            //Config examples
            //this.Plugins.Add(new PostmanFeature());
            //Plugins.Add(new CorsFeature());

            InitializeAppSettings();

            Plugins.Add(new RazorFormat
            {
                LoadFromAssemblies = { typeof(SharedEmbeddedResources).Assembly }
            });

            SetConfig(new HostConfig
            {
                DebugMode = true,
                EmbeddedResourceBaseTypes = { typeof(AppHost), typeof(SharedEmbeddedResources) }
            });

            JsConfig.EmitCamelCaseNames = true;

            Plugins.Add(new RazorFormat());
            Plugins.Add(new ServerEventsFeature());

            MimeTypes.ExtensionMimeTypes["jsv"] = "text/jsv";

            SetConfig(new HostConfig
            {
                DebugMode = AppSettings.Get("DebugMode", false),
                DefaultContentType = MimeTypes.Json,
                AllowFileExtensions = { "jsx" },
            });

            CustomErrorHttpHandlers.Remove(HttpStatusCode.Forbidden);

            //Register all Authentication methods you want to enable for this web app.
            Plugins.Add(new AuthFeature(
                () => new AuthUserSession(),
                new IAuthProvider[] {
                    new TwitterAuthProvider(AppSettings)   //Sign-in with Twitter
                }));

            container.RegisterAutoWiredAs<MemoryChatHistory, IChatHistory>();

            var redisHost = AppSettings.GetString("RedisHost");
            if (redisHost != null)
            {
                container.Register<IRedisClientsManager>(new RedisManagerPool(redisHost));

                container.Register<IServerEvents>(c =>
                    new RedisServerEvents(c.Resolve<IRedisClientsManager>()));
                container.Resolve<IServerEvents>().Start();
            }

            // This route is added using Routes.Add and ServiceController.RegisterService due to
            // using ILMerge limiting our AppHost : base() call to one assembly.
            // If two assemblies are used, the base() call searchs the same assembly twice due to the ILMerged result.
            Routes.Add<NativeHostAction>("/nativehost/{Action}");
            ServiceController.RegisterService(typeof(NativeHostService));
        }
Example #14
0
        public override void Configure(Container container)
        {
            Plugins.Add(new RazorFormat());
            Plugins.Add(new MsgPackFormat());
            Plugins.Add(new SwaggerFeature { UseBootstrapTheme = true });

            typeof(SwaggerResources)
                .AddAttributes(new RestrictAttribute { VisibilityTo = RequestAttributes.None });
            typeof(SwaggerResource)
                .AddAttributes(new RestrictAttribute { VisibilityTo = RequestAttributes.None });

            var metadata = (MetadataFeature)Plugins.First(x => x is MetadataFeature);
            metadata.IndexPageFilter = page => {
                page.OperationNames.Sort((x,y) => y.CompareTo(x));
            };

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

            InitData(container);

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

            this.CustomErrorHttpHandlers[HttpStatusCode.ExpectationFailed] = new RazorHandler("/expectationfailed");
        }
Example #15
0
        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The IoC container.</param>
        public override void Configure(Container container)
        {
            // Configure ServiceStack host
            ConfigureHost(container);

            // Configure JSON serialization properties
            ConfigureSerialization(container);

            // Configure application settings and configuration parameters
            ConfigureApplication(container);

            // Configure database schema synchronization
            ConfigureDataSchema(container);

            // Configure ServiceStack database connections
            ConfigureDataConnection(container);

            // Configure caching mechanism
            ConfigureCache(container);

            // Configure ServiceStack Authentication plugin
            ConfigureUserAuth(container);

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

            // Configure ServiceStack Razor views
            ConfigureView(container);

            // Configure various system tools / features
            ConfigureTools(container);
        }
Example #16
0
        /// <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)
        {
            //Config examples
            //this.Plugins.Add(new PostmanFeature());
            //Plugins.Add(new CorsFeature());

            Plugins.Add(new RazorFormat
                {
                    LoadFromAssemblies = { typeof(CefResources).Assembly },
                });

            SetConfig(new HostConfig
                {
                    DebugMode = true,
                    EmbeddedResourceBaseTypes = { typeof(AppHost), typeof(CefResources) }
                });

            Routes.Add<NativeHostAction>("/nativehost/{Action}");
            ServiceController.RegisterService(typeof(NativeHostService));

            var allKeys = AppSettings.GetAllKeys();
            if (!allKeys.Contains("platformsClassName"))
                AppSettings.Set("platformsClassName", "console");
            if (!allKeys.Contains("PlatformCss"))
                AppSettings.Set("PlatformCss", "mac.css");
            if (!allKeys.Contains("PlatformJs"))
                AppSettings.Set("PlatformJs", "mac.js");
        }
Example #17
0
        public override void Configure(Container container)
        {
            HostConfig.Instance.DefaultRedirectPath = DefaultRedirectPath;

            HostConfig.Instance.MapExceptionToStatusCode = new Dictionary<Type, int>
            {
                {typeof (InvalidOperationException), 422},
                {typeof (ResourceNotFoundException), 404},
                {typeof (FileNotFoundException), 404},
                {typeof (DirectoryNotFoundException), 404},
                {typeof (Implementations.Security.AuthenticationException), 401}
            };

            HostConfig.Instance.DebugMode = true;

            HostConfig.Instance.LogFactory = LogManager.LogFactory;

            // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
            // Custom format allows images
            HostConfig.Instance.EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat;

            container.Adapter = _containerAdapter;

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type, Authorization"));

            //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
            //    new SessionAuthProvider(_containerAdapter.Resolve<ISessionContext>()),
            //}));

            HostContext.GlobalResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
        }
Example #18
0
 private static void RegisterInstances(Funq.Container container)
 {
     container.RegisterAutoWiredAs <ASEExceptionLogger, ILogger>();
     container.RegisterAutoWiredAs <ContactManager, IContactManager>();
     container.RegisterAutoWiredAs <CohortRulesProcessor, ICohortRulesProcessor>();
     container.RegisterAutoWiredAs <NGManager, INGManager>();
 }
Example #19
0
        public override void Configure(Funq.Container container)
        {
            // MsgPack
            container.Register <IMsgPackBackendServiceClient>(c =>
            {
                var client            = new MsgPackBackendServiceClient("http://localhost:1337/");
                client.ResponseFilter = response =>
                {
                    Trace.WriteLine($"MsgPackBSC: [{client.Elapsed.TotalMilliseconds}msecs]  {response.ResponseUri} ({response.ContentLength} bytes)");
                };
                client.AddHeader("X-ApiKey", "Dummy");
                return(client);
            }).ReusedWithin(ReuseScope.None);

            // Wire
            container.Register <IWireBackendServiceClient>(c =>
            {
                var client            = new WireBackendServiceClient("http://localhost:1337/");
                client.ResponseFilter = response =>
                {
                    Trace.WriteLine($"WireBSC: [{client.Elapsed.TotalMilliseconds}msecs]  {response.ResponseUri} ({response.ContentLength} bytes)");
                };
                client.AddHeader("X-ApiKey", "Dummy");
                return(client);
            }).ReusedWithin(ReuseScope.None);
        }
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory();

            SetConfig(new HostConfig
            {
                DebugMode = true,
                EmbeddedResourceSources = { Assembly.GetExecutingAssembly() },
            });

            Plugins.Add(new RazorFormat
            {
                LoadFromAssemblies = { typeof(RockstarsService).Assembly }
            });
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());

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

            using (var db = container.Resolve<IDbConnectionFactory>().OpenDbConnection())
            {
                db.CreateTableIfNotExists<Rockstar>();
                db.InsertAll(RockstarsService.SeedData);
            }

            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
            this.CustomErrorHttpHandlers[HttpStatusCode.Unauthorized] = new RazorHandler("/login");
        }
Example #21
0
        public override void Configure(Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = false;

            //Uncomment to change the default ServiceStack configuration
            //SetConfig(new EndpointHostConfig {
            //});

            //Use Elmah with ServiceStack
            LogManager.LogFactory = new ElmahLogFactory(new NullLogFactory());

            //Make the default lifetime of objects limited to request
            container.DefaultReuse = ReuseScope.Request;

            //Uncomment to use Entity Framework
            //RegisterEfServicesAndRepositories(container);
            RegisterOrmLiteServicesAndRepositories(container);
            RegisterCacheAndStorage(container);

            //Enable Authentication
            //ConfigureAuth(container);

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
Example #22
0
        public override void Configure(Container container)
        {
            Plugins.Add(new RegistrationFeature());
            Plugins.Add (
                new AuthFeature
                (
                    () => new AuthUserSession(),
                    new IAuthProvider[]
                    {
                        new BasicAuthProvider(),
                        new CustomCredentialsAuthProvider()
                    }
                ) {HtmlRedirect = "/common/login" }
            );
            Plugins.Add(new RazorFormat());

            SetConfig(new EndpointHostConfig {
                DefaultContentType = ContentType.Json,
                CustomHttpHandlers = {
                    { HttpStatusCode.NotFound, new RazorHandler("/notfound") }
                }
            });

            container.Register<IRedisClientsManager>(new PooledRedisClientManager("localhost:6379"));
            UserRepository = new RedisAuthRepository(container.Resolve<IRedisClientsManager>());
            container.Register<IUserAuthRepository>(UserRepository);
        }
 /// <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());
     //Routes.Add<Hello>("/hello/{Name}");
 }
		public override void Configure(Container container)
		{
			SetConfig(new EndpointHostConfig
			{
				UseBclJsonSerializers = true,
			});
		}
Example #25
0
            //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();
                }
            }
Example #26
0
        /// <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)
        {
            JsConfig.EmitCamelCaseNames = true;

            Plugins.Add(new ServerEventsFeature());

            SetConfig(new HostConfig
            {
                DebugMode                      = AppSettings.Get("DebugMode", false),
                DefaultContentType             = MimeTypes.Json,
                AddRedirectParamsToQueryString = true,
            });

            CustomErrorHttpHandlers.Remove(HttpStatusCode.Forbidden);

            //Register all Authentication methods you want to enable for this web app.
            Plugins.Add(new AuthFeature(
                            () => new AuthUserSession(),
                            new IAuthProvider[] {
                new TwitterAuthProvider(AppSettings)       //Sign-in with Twitter
            }));

            container.RegisterAutoWiredAs <MemoryChatHistory, IChatHistory>();

            var redisHost = AppSettings.GetString("RedisHost");

            if (redisHost != null)
            {
                container.Register <IRedisClientsManager>(new RedisManagerPool(redisHost));

                container.Register <IServerEvents>(c =>
                                                   new RedisServerEvents(c.Resolve <IRedisClientsManager>()));
                container.Resolve <IServerEvents>().Start();
            }
        }
Example #27
0
        public override void Configure(Container container)
        {
            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new RazorFormat());
            Plugins.Add(new RequestLogsFeature());

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(ContactsServices).Assembly);

            container.Register<IDbConnectionFactory>(
                c => new OrmLiteConnectionFactory("db.sqlite", SqliteDialect.Provider) {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

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

                db.Insert(new Contact { Name = "Kurt Cobain", Email = "*****@*****.**", Age = 27 });
                db.Insert(new Contact { Name = "Jimi Hendrix", Email = "*****@*****.**", Age = 27 });
                db.Insert(new Contact { Name = "Michael Jackson", Email = "*****@*****.**", Age = 50 });
            }

            UseDbEmailer(container);
            //UseSmtpEmailer(container); //Uncomment to use SMTP instead

            //ConfigureRabbitMqServer(container); //Uncomment to start accepting requests via Rabbit MQ
        }
Example #28
0
 public override void Configure(Funq.Container container)
 {
     LogManager.LogFactory = new ConsoleLogFactory();
     Plugins.Add(new RazorFormat());
     Routes
     .Add <Hello>("/hello/{Name}");
 }
Example #29
0
        public override void Configure(Container container)
        {
            if (EnableRazor)
                Plugins.Add(new RazorFormat());

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new RequestInfoFeature());
            Plugins.Add(new RequestLogsFeature());
            Plugins.Add(new ServerEventsFeature());

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(AutoValidationValidator).Assembly);


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

            using (var db = container.Resolve<IDbConnectionFactory>().OpenDbConnection())
            {
                db.DropAndCreateTable<Rockstar>(); //Create table if not exists
                db.Insert(Rockstar.SeedData); //Populate with seed data
            }

            SetConfig(new HostConfig {
                AdminAuthSecret = "secret",
                DebugMode = true,
            });
        }
Example #30
0
		public override void Configure(Container container)
		{
			//Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
			base.SetConfig(new EndpointHostConfig
			{
				GlobalResponseHeaders =
					{
						{ "Access-Control-Allow-Origin", "*" },
						{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
					},
			});

			container.Register<IResourceManager>(new ConfigurationResourceManager());

			container.Register(c => new ExampleConfig(c.Resolve<IResourceManager>()));
			var appConfig = container.Resolve<ExampleConfig>();

			container.Register<IDbConnectionFactory>(c =>
				new OrmLiteConnectionFactory(
					appConfig.ConnectionString.MapHostAbsolutePath(),
					SqliteOrmLiteDialectProvider.Instance));

			ConfigureDatabase.Init(container.Resolve<IDbConnectionFactory>());


			//register different cache implementations depending on availability
			const bool hasRedis = false;
			if (hasRedis)
				container.Register<ICacheClient>(c => new BasicRedisClientManager());
			else
				container.Register<ICacheClient>(c => new MemoryCacheClient());


			log.InfoFormat("AppHost Configured: " + DateTime.Now);
		}
Example #31
0
		public override void Configure(Container container)
		{
			//Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
			base.SetConfig(new EndpointHostConfig
			{
				GlobalResponseHeaders =
					{
						{ "Access-Control-Allow-Origin", "*" },
						{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH" },
					},
				  DefaultContentType = ContentType.Json 
			});
						
			var config = new AppConfig(new ConfigurationResourceManager());
			container.Register(config);
			
			
			OrmLiteConfig.DialectProvider= FirebirdOrmLiteDialectProvider.Instance;
			
			IDbConnectionFactory dbFactory = new OrmLiteConnectionFactory(
				ConfigUtils.GetConnectionString("ApplicationDb"));
			
			container.Register<Factory>(
				new Factory(){
					DbFactory=dbFactory
				}
			);
									
			ConfigureAuth(container);
			
			log.InfoFormat("AppHost Configured: " + DateTime.Now);
		}
        public StatusItemBurritoDayView(Container container)
        {
            this.menu = new NSMenu();

            this.menu.AddItem(this.refreshMenuItem);
            this.menu.AddItem(this.launchMenuItem);

            this.menu.AddItem(NSMenuItem.SeparatorItem);

            this.menu.AddItem(this.durationMenuItem);
            this.menu.AddItem(this.locationMenuItem);

            this.menu.AddItem(this.separatorMenuItem);;

            this.menu.AddItem(this.dismissMenuitem);
            this.menu.AddItem(this.quitMenuItem);

            this.launchMenuItem.Activated += delegate {
                var handler = this.urlActivated;
                if (handler != null)
                {
                    handler(this, "http://isitburritoday.com");
                }
            };
            this.quitMenuItem.Activated += (sender, e) =>
                NSApplication.SharedApplication.Terminate(sender as NSObject);

            this.presenters = new IDisposable[]
            {
                container.Resolve<BurritoDayPresenter, IBurritoDayView>(this),
                container.Resolve<UrlActivationPresenter, IUrlActivationView>(this),
            };
        }
			public override void Configure(Container container)
			{
                HostContext.Config.GlobalResponseHeaders.Clear();

				//Signal advanced web browsers what HTTP Methods you accept
				base.SetConfig(new HostConfig
				{
					GlobalResponseHeaders =
					{
						{ "Access-Control-Allow-Origin", "*" },
						{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
					},
				});

				this.GlobalRequestFilters.Add((req, res, dto) =>
				{
					var requestFilter = dto as RequestFilter;
					if (requestFilter != null)
					{
						res.StatusCode = requestFilter.StatusCode;
						if (!requestFilter.HeaderName.IsNullOrEmpty())
						{
							res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue);
						}
					}
				});
			}
Example #34
0
        public static void Configure(Container container, PhoneApplicationFrame root)
        {
            container.Register<IJiraService>(c => new JiraService{Store = c.Resolve<IDocumentStore>()});
            container.Register<IScheduler>(c => new Scheduler());

            container.Register(c => new SignInCommandHandler{Bus = c.Resolve<IBus>()});
            container.Register(c => new SyncHandler{Bus = c.Resolve<IBus>(), Jira = c.Resolve<IJiraService>()});
            container.Register(
                c => new SyncProjectHandler
                    {
                        Bus = c.Resolve<IBus>(),
                        Store = c.Resolve<IDocumentStore>(),
                        Jira = c.Resolve<IJiraService>(),
                        Scheduler = c.Resolve<IScheduler>()
                    });
            container.Register(c => new SyncNewlyDiscoveredProjectsByDefaultHandler {Bus = c.Resolve<IBus>()});

            container.Register(c => new ProfileLoggedInEventHandler { Store = c.Resolve<IDocumentStore>() });

            var bus = container.Resolve<IBus>();

            bus.RegisterHandler<SignInCommandHandler, SignInCommand>();
            bus.RegisterHandler<SyncHandler, ApplicationLoadedEvent>();
            bus.RegisterHandler<ProfileLoggedInEventHandler, LoggedInEvent>();
            bus.RegisterHandler<SyncHandler, LoggedInEvent>();
            bus.RegisterHandler<SyncProjectHandler, ProjectsDiscoveredEvent>();
            bus.RegisterHandler<SyncProjectHandler, SyncProjectCommand>();
            bus.RegisterHandler<SyncNewlyDiscoveredProjectsByDefaultHandler, DiscoveredNewProjectEvent>();
        }
        public void should_be_able_to_get_service_impl()
        {
            var c = new Container();
            c.EasyRegister<IFoo, Foo>();

            Assert.IsInstanceOf<Foo>(c.Resolve<IFoo>());
        }
		public override void Configure(Container container)
		{
			JsConfig.DateHandler = JsonDateHandler.ISO8601;	

			container.Register<IDbConnectionFactory>(c =>
				new OrmLiteConnectionFactory(
					"~/App_Data/db.sqlite".MapHostAbsolutePath(),
					SqliteOrmLiteDialectProvider.Instance));

			var resetMovies = container.Resolve<ResetMoviesService>();
			resetMovies.Post(null);

			Routes
			  .Add<Movie>("/movies")
			  .Add<Movie>("/movies/{Id}")
			  .Add<Movies>("/movies")
			  .Add<Movies>("/movies/genres/{Genre}");

			SetConfig(new EndpointHostConfig
			{
				GlobalResponseHeaders = {
						{ "Access-Control-Allow-Origin", "*" },
						{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
						{ "Access-Control-Allow-Headers", "Content-Type, X-Requested-With" },
					},
					//EnableFeatures = onlyEnableFeatures,
					//DebugMode = true, //Show StackTraces for easier debugging
			});

		}
Example #37
0
            public override void Configure(Container container)
            {
                this.RequestFilters.Add((req, res, dto) =>
                {
                    var requestFilter = dto as RequestFilter;
                    if (requestFilter != null)
                    {
                        res.StatusCode = requestFilter.StatusCode;
                        if (!requestFilter.HeaderName.IsNullOrEmpty())
                        {
                            res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue);
                        }
                        res.Close();
                    }

                    var secureRequests = dto as IRequiresSession;
                    if (secureRequests != null)
                    {
                        res.ReturnAuthRequired();
                    }
                });

                this.Container.Register<IDbConnectionFactory>(c =>
                    new OrmLiteConnectionFactory(
                        "~/App_Data/db.sqlite".MapHostAbsolutePath(),
                        SqliteOrmLiteDialectProvider.Instance));

                this.Container.Register<ICacheClient>(new MemoryCacheClient());

                var dbFactory = this.Container.Resolve<IDbConnectionFactory>();
                dbFactory.Exec(dbCmd => dbCmd.CreateTable<Movie>(true));

                var resetMovies = this.Container.Resolve<ResetMoviesService>();
                resetMovies.Post(null);
            }
Example #38
0
        public static void Configure(PhoneApplicationFrame rootFrame)
        {
            DocumentStore = new DocumentStore();
            Container = new Container();

            Container.Register<IDocumentStore>(c => new DocumentStore());
            Container.Register<IBus>(c => new Bus(c));

            Container.Register(c => new ActivityNewActivityHandler { Bus = c.Resolve<IBus>(), DocumentStore = DocumentStore });
            Container.Register(c => new TestModeActivatedHandler { Bus = c.Resolve<IBus>() });
            Container.Register(c => new ActivateTestModeHandler { Bus = c.Resolve<IBus>() });
            Container.Register(c => new ClearCacheHandler { DocumentStore = c.Resolve<IDocumentStore>() });
            Container.Register(c => new Contexts.Review.Domain.ClearCacheHandler { DocumentStore = c.Resolve<IDocumentStore>() });

            var bus = Container.Resolve<IBus>();

            bus.RegisterHandler<ActivityNewActivityHandler, NewActivityEvent>();
            bus.RegisterHandler<TestModeActivatedHandler, TestModeActivatedEvent>();
            bus.RegisterHandler<ActivateTestModeHandler, ActivateCommand>();
            bus.RegisterHandler<Contexts.Settings.ClearCacheHandler, ClearCacheCommand>();
            bus.RegisterHandler<Contexts.Review.Domain.ClearCacheHandler, ClearCacheCommand>();

            Contexts.Import.Module.Configure(Container);
            Contexts.Import.ModuleUi.Configure(Container, rootFrame);

            Contexts.Review.Module.Confiure(Container);
        }
        private static void RegisterRepositories(Container container)
        {
            container.Register<IUserTokenRepository>(
                c => new UserTokenRecordRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IServiceProviderRepository>(
                c => new ServiceProviderRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IAuthProviderFactory>(
                c => new AuthProviderFactory(c.Resolve<IEnumerable<IAuthProviderInstance>>()));

            container.Register<IApplicationRepository>(
                c => new ApplicationRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IApplicationServiceRepository>(
                c => new ApplicationServiceRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IAccountApplicationRepository>(
                c => new AccountApplicationRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IAccountRepository>(
                c => new AccountRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IAccountUserRepository>(
                c => new AccountUserRepository(c.Resolve<IDataConnectionProvider>()));

            container.Register<IUserRepository>(
                c => new UserRepository(c.Resolve<IDataConnectionProvider>()));
        }
Example #40
0
 public override void Configure(Funq.Container container)
 {
     ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
     Routes.
     Add <Contact>("/contacts").
     Add <Contact>("/contacts/{id}");
     container.Register <IRedisClientsManager>(new BasicRedisClientManager());
 }
Example #41
0
            public override void Configure(Funq.Container container)
            {
                var dbConnectionFactory = new OrmLiteConnectionFactory(HttpContext.Current.Server.MapPath("~/App_Data/data.txt"),
                                                                       SqliteDialect.Provider);

                container.Register <IDbConnectionFactory>(dbConnectionFactory);
                container.RegisterAutoWired <TrackedRepository>();
            }
Example #42
0
        public override void Configure(Funq.Container container)
        {
            SetConfig(new HostConfig {
                DebugMode = true
            });

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
        }
Example #43
0
            public override void Configure(Funq.Container container)
            {
                _pushBroker.RegisterGcmService(new GcmPushChannelSettings(AppSettings.GetString("AndroidServerKey")));

                container.Register(c => _pushBroker).ReusedWithin(ReuseScope.Container);
                container.Register(new ServerSettings {
                    ApiKey = AppSettings.GetString("ApiKey")
                });
            }
Example #44
0
        public override void Configure(Funq.Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory();
            Plugins.Add(new RazorFormat());


            SetConfig(new EndpointHostConfig {
                DebugMode = true
            });
        }
Example #45
0
        public override void Configure(Funq.Container container)
        {
            JsConfig.ExcludeTypeInfo = true;

            Logger.Info("Reading global configuration");
            //register any dependencies your services use, e.g:
            //container.Register<ICacheClient>(new MemoryCacheClient());
            WebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);

            Logger.Info("Configure ServiceStack EndpointHostConfig");
            base.SetConfig(new EndpointHostConfig {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                                   },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"     },
                    { "Cache-Control",                "no-cache, no-store, must-revalidate" },
                    { "Pragma",                       "no-cache"                            },
                    { "Expires",                      "0"                                   }
                },
                EnableAccessRestrictions = true,
                DebugMode                = true, //Enable StackTraces in development
                WebHostUrl               = WebConfig.AppSettings.Settings["baseUrl"].Value,
                WriteErrorsToResponse    = true,
                DefaultContentType       = ServiceStack.Common.Web.ContentType.Json,
                MapExceptionToStatusCode =
                {
                    { typeof(NotFoundException), 404 },
                }
            });

            Logger.Info("Load Plugins");
            LoadPlugins();

            Logger.Info("Configure Service Exception Handler");
            this.ServiceExceptionHandler = (httpReq, request, ex) => {
                if (EndpointHost.Config != null && EndpointHost.Config.ReturnsInnerException && ex.InnerException != null && !(ex is IHttpError))
                {
                    ex = ex.InnerException;
                }
                ResponseStatus responseStatus = ex.ToResponseStatus();
                if (EndpointHost.DebugMode)
                {
                    responseStatus.StackTrace = DtoUtils.GetRequestErrorBody(request) + "\n" + ex;
                }
                return(DtoUtils.CreateErrorResponse(request, ex, responseStatus));
            };

            Logger.Info("Register ContentType Filters");
            this.ContentTypeFilters.Register("application/opensearchdescription+xml", OpenSearchDescriptionService.OpenSearchDescriptionSerializer, OpenSearchDescriptionService.OpenSearchDescriptionDeserializer);

            this.PreRequestFilters.Insert(0, (httpReq, httpRes) => {
                httpReq.UseBufferedStream = true;
            });
        }
Example #46
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Funq.Container container)
        {
            //Register Redis Client Manager singleton in ServiceStack's built-in Func IOC
            container.Register(s => new RepositoryFactories());
            container.Register <IRepositoryProvider>(c => new RepositoryProvider(c.TryResolve <RepositoryFactories>())).ReusedWithin(ReuseScope.None);
            container.Register <IOpfcUow>(c => new OpfcUow(c.TryResolve <IRepositoryProvider>())).ReusedWithin(ReuseScope.None);

            container.Register(s => new ServiceFactories(s.Resolve <IOpfcUow>())).ReusedWithin(ReuseScope.None);
            container.Register <IServiceProvider>(c => new ServiceProvider(c.TryResolve <ServiceFactories>())).ReusedWithin(ReuseScope.None);
            container.Register <IServiceUow>(c => new ServiceUow(c.TryResolve <IServiceProvider>())).ReusedWithin(ReuseScope.None);

            container.Register <ITask>(t => new CompositeTask(new AutoMapperConfigTask()));
            container.Resolve <ITask>().Execute();
        }
Example #47
0
        public override void Configure(Funq.Container container)
        {
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
            Plugins.Add(new RazorFormat());

            var ormLiteConnectionFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["studentDbConn"].ConnectionString,
                                                                        ServiceStack.OrmLite.SqlServer.SqlServerOrmLiteDialectProvider.Instance);


            container.Register <IDbConnectionFactory>(ormLiteConnectionFactory);
            container.Register(c => new StudentDbRepository()).ReusedWithin(ReuseScope.Request);

            container.RegisterAutoWired <StudentDbRepository>();

            DbInitializer.InitializeDb(ormLiteConnectionFactory);
        }
Example #48
0
        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();
                    }
                }
            });
        }
Example #49
0
        public TestAppHost(Funq.Container container, params Assembly[] serviceAssemblies)
        {
            this.container = container ?? new Container();
            if (serviceAssemblies.Length == 0)
            {
                serviceAssemblies = new[] { Assembly.GetExecutingAssembly() }
            }
            ;

            EndpointHostConfig.Instance.ServiceManager = new ServiceManager(true, serviceAssemblies);

            this.Config = EndpointHostConfig.Instance;

            this.ContentTypeFilters = new HttpResponseFilter();
            this.PreRequestFilters  = new List <Action <IHttpRequest, IHttpResponse> >();
            this.RequestFilters     = new List <Action <IHttpRequest, IHttpResponse, object> >();
            this.ResponseFilters    = new List <Action <IHttpRequest, IHttpResponse, object> >();
            this.CatchAllHandlers   = new List <HttpHandlerResolverDelegate>();
        }
Example #50
0
        public TestAppHost(Funq.Container container, params Assembly[] serviceAssemblies)
        {
            this.container = container ?? new Container();
            if (serviceAssemblies.Length == 0)
            {
                serviceAssemblies = new[] { Assembly.GetExecutingAssembly() }
            }
            ;

            var createInstance = EndpointHostConfig.Instance;

            this.Config = EndpointHost.Config = new EndpointHostConfig(
                GetType().Name,
                new ServiceManager(true, serviceAssemblies));

            this.ContentTypeFilters = new HttpResponseFilter();
            this.RequestFilters     = new List <Action <IHttpRequest, IHttpResponse, object> >();
            this.ResponseFilters    = new List <Action <IHttpRequest, IHttpResponse, object> >();
            this.HtmlProviders      = new List <StreamSerializerResolverDelegate>();
            this.CatchAllHandlers   = new List <HttpHandlerResolverDelegate>();
        }
Example #51
0
        private void ConfigureAuth(Funq.Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory();
            container.Register <IUserAuthRepository>(c => new UserAuthRepository(c.Resolve <IDbConnectionFactory>()));

            //Register all Authentication methods you want to enable for this web app.
            this.Plugins.Add(new AuthFeature(
                                 () => new Session(), //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 BasicAuthProvider()               //Sign-in with Basic Auth
            }));

            //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<Registration>>();
        }
Example #52
0
        public override void Configure(Funq.Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            //Configure User Defined REST Paths
            Routes
            .Add <Hello>("/hello")
            .Add <Hello>("/hello/{Name*}")
            .Add <Hello>("/todos")
            .Add <Hello>("/todos/{Id}")
            .Add <Project>("/projects")
            .Add <Project>("/projects/{Id}")
            .Add <Note>("/notes")
            .Add <Note>("/notes/{Id}")
            .Add <Note>("/projects/{ProjectId}/notes")
            .Add <Note>("/projects/{ProjectId}/notes/{Id}");

            //Change the default ServiceStack configuration
            //SetConfig(new EndpointHostConfig {
            //    DebugMode = true, //Show StackTraces in responses in development
            //});

            //Enable Authentication
            //ConfigureAuth(container);

            //Register all your dependencies
            container.Register(new TodoRepository());

            //Register In-Memory Cache provider.
            //For Distributed Cache Providers Use: PooledRedisClientManager, BasicRedisClientManager or see: https://github.com/ServiceStack/ServiceStack/wiki/Caching
            container.Register <ICacheClient>(new MemoryCacheClient());
            container.Register <ISessionFactory>(c =>
                                                 new SessionFactory(c.Resolve <ICacheClient>()));
            //container.Register<NoteService>(c => new NoteService(c.Resolve<IDocumentSession>()));

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
Example #53
0
        public TestAppHost(Funq.Container container, params Assembly[] serviceAssemblies)
        {
            this.container = container ?? new Container();
            if (serviceAssemblies.Length == 0)
            {
                serviceAssemblies = new[] { Assembly.GetExecutingAssembly() }
            }
            ;

            var createInstance = EndpointHostConfig.Instance;

            this.Config = EndpointHost.Config = new EndpointHostConfig(
                GetType().Name,
                new ServiceManager(this.container, serviceAssemblies).Init());

            this.ContentTypeses      = new ContentTypes();
            this.PreRequestFilters   = new List <Action <IHttpRequest, IHttpResponse> >();
            this.RequestFilters      = new List <Action <IHttpRequest, IHttpResponse, object> >();
            this.ResponseFilters     = new List <Action <IHttpRequest, IHttpResponse, object> >();
            this.ViewEngines         = new List <IViewEngine>();
            this.CatchAllHandlers    = new List <HttpHandlerResolverDelegate>();
            this.VirtualPathProvider = new FileSystemVirtualPathProvider(this);
        }
Example #54
0
        public override void Configure(Funq.Container container)
        {
            // Register any dependencies your services use here.

            //Config examples
            //this.Plugins.Add(new PostmanFeature());

            //支持跨域 方式1
            //his.Plugins.Add(new CorsFeature());
            //相当于使用了默认配置
            //CorsFeature(allowedOrigins: "*",allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",allowedHeaders: "Content-Type",allowCredentials: false);
            //如果仅仅允许GET和POST的请求支持CORS,则只需要改为:
            //Plugins.Add(new CorsFeature(allowedMethods: "GET, POST"));

            //对应JsonP 跨域提交 方式2
            //this.GlobalResponseFilters.Add((req, res, dto) =>
            //{
            // var func = req.QueryString.Get("callback");
            // if (!func.IsNullOrEmpty())
            // {
            // res.AddHeader("Content-Type", "text/html");
            // res.Write("<script type='text/javascript'>{0}({1});</script>".FormatWith(func, dto.ToJson()));
            // res.Close();
            // }
            //});

            //支持跨域 方式3
            base.SetConfig(new HostConfig()
            {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                               },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                    { "Access-Control-Allow-Headers", "Content-Type"                    },
                },
            });
        }
Example #55
0
        public override void Configure(Funq.Container container)
        {
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new ConcordAPI.ServiceInterface.ConcordyaBasicAuthProvider()     //Sign-in with Basic Auth
            }));

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

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

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(
                                                          new AppSettings().Get(
                                                              "ConcordAPI.Properties.Settings.LocalSQLConnectionString",
                                                              db_conn_string), SqlServerDialect.Provider));

            //container.Resolve
            var userRepository = new OrmLiteAuthRepository <UserAccount, UserAccountDetail>(container.Resolve <IDbConnectionFactory>());

            container.Register <IUserAuthRepository>(userRepository);
            InitialDbTables(container, userRepository);
        }
Example #56
0
        private static void InitialDbTables(Funq.Container container, OrmLiteAuthRepository <UserAccount, UserAccountDetail> userRepository)
        {
            string hash, salt;

            new SaltedHash().GetHashAndSaltString("password1", out hash, out salt);

            userRepository.DropAndReCreateTables();
            using (var dbConnection = container.Resolve <IDbConnectionFactory>().OpenDbConnection())
            {
                dbConnection.CreateTable <Bill>(true);
                dbConnection.CreateTable <Invoice>(true);
                dbConnection.CreateTable <AddressBranching>(true);
                dbConnection.CreateTable <Address>(true);
                dbConnection.CreateTable <Company>(true);
                dbConnection.CreateTable <Category>(true);
            }
            userRepository.CreateUserAuth(new UserAccount
            {
                UserName = "******",
                Password = hash,
                FullName = "Cheng Zhang",
                Email    = "*****@*****.**",
                Salt     = salt,
                Roles    = new List <string> {
                    RoleNames.Admin
                },
                Permissions = new List <string> {
                    "Get"
                },
                CreatedDate     = DateTime.Now,
                Create_On       = DateTime.Now,
                LastLoginTime   = DateTime.Now,
                Last_Updated_By = 0,
                Last_Updated_On = DateTime.Now
            }, "password1");
        }
Example #57
0
    /// <summary>
    /// Configure the given container with the
    /// registrations provided by the funqlet.
    /// </summary>
    /// <param name="container">Container to register.</param>
    public override void Configure(Funq.Container container)
    {
        ServiceStack.OrmLite.OrmLiteConfig.CommandTimeout = 60;
        WebEas.Log.WebEasNLogLogger.Application           = "REG";

        base.Configure(container);

        this.SetConfig(new HostConfig
        {
            WsdlServiceNamespace = "http://schemas.webeas.sk/office/esam/office/1.0",
            SoapServiceName      = "EsamOfficeReg",
#if DEBUG || DEVELOP || INT || ITP
            DebugMode      = true,
            EnableFeatures = Feature.All.Remove(this.disableFeaturesDebug),
#else
            DebugMode      = false,
            EnableFeatures = Feature.All.Remove(this.disableFeatures),
#endif
            DefaultContentType = MimeTypes.Json,
            AllowJsonpRequests = true
        });

        //JsConfig<List<FilesDto>>.DeSerializeFn = data => JsonSerializer.DeserializeFromString<List<FilesDto>>(data);

        //JsConfig.ThrowOnDeserializationError = true;
        //JsConfig.OnDeserializationError = (object instance, System.Type propertyType, string propertyName, string propertyValueStr, System.Exception ex) =>
        //{
        //    Console.WriteLine(ex.Message);
        //};

#if !DEBUG
        ConfigureMessageServiceForLongOperations <ServiceModel.Office.Reg.Dto.RegLongOperationStartDto>(container);
#endif
        //Routes.Add<IsoMessageDto>("/AckMsg");
        container.AddScoped <IRegRepository, RegRepository>();
    }
 public override void Configure(Funq.Container container)
 {
     container.Register <ICacheClient>(new MemoryCacheClient());
 }
Example #59
0
 protected override void Configure(Funq.Container container)
 {
 }
Example #60
0
 protected abstract void Configure(Funq.Container container);