예제 #1
0
        private void Initialize(string path, IPrincipal user)
        {
            ServiceContainer = GlobalContainer.CreateChild();

            this.Id   = Guid.NewGuid();
            this.User = user;

            var info = PathInfoBuilder.Build(path);

            if (info == null)
            {
                return;
            }
            this.ServiceUnitName = info.ServiceUnitName;
            this.Version         = info.Version;
            this.Role            = info.Role;
            this.Request         = new ServiceUnitRequest(this, info);
            this.Configuration   = ServiceConfigurationLoader.Load(info.ServiceUnitName, info.Version, info.Role);

            var logConfig = LogConfiguration.CreateLogAdapterSetting(this.Configuration.Raw);

            var       logger   = new Logger(info.ProcessPath, logConfig);
            IIdentity identity = (this.User != null) ? this.User.Identity : new GenericIdentity("Anonymous");

            this.LogContext = new LogContext(logger, this.Id, identity);

            ServiceContainer.AddInstance(this);
            ServiceContainer.AddInstance(this.LogContext);
            ServiceContainer.AddInstance(this.Configuration);
        }
예제 #2
0
        ///
        public override void Initialize()
        {
            base.Initialize();

            LoadUserInfos();

            // Load modules
            GlobalContainer.LoadComponents <IClientModule>(TypeLoadFilter);
            GlobalContainer.LoadComponents <IModuleShell>(TypeLoadFilter);

            // Get types
            var moduleTypes = GlobalContainer.GetRegisteredImplementations(typeof(IClientModule));
            var shellTypes  = GlobalContainer.GetRegisteredImplementations(typeof(IModuleShell)).ToArray();

            // Get assemblies
            Assemblies.AddRange(moduleTypes.Union(shellTypes).Distinct().Select(t => t.Assembly).Distinct().ToList());

            // Raise load event for AssemblyConfiguration
            RaiseAssemblyConfigurationLoaded(new AssemblyConfiguration
            {
                Assemblies = Assemblies.Select(m => new AssemblyConfig(Path.GetFileName(m.Location))).ToList()
            });

            // Raise AssemblyLoaded event for earch assembly
            foreach (var module in Assemblies)
            {
                RaiseAssemblyLoaded(new AssemblyConfig(Path.GetFileName(module.Location)));
            }

            RaiseAssembliesLoaded(Assemblies);
        }
        private JObject LoadConfig(string path, string env, bool createEmpty = true)
        {
            //HostingEnvironment
            var     dir       = GlobalContainer.GetService <IApplicationEnvironment>().MapPath(path);
            JObject envConfig = null;

            if (!string.IsNullOrEmpty(env))
            {
                var configFileName = System.IO.Path.Combine(dir, string.Format(EnvConfigFileNameFormat, env));
                if (File.Exists(configFileName))
                {
                    envConfig = JObject.Parse(File.ReadAllText(configFileName));
                }
                else
                {
                    if (createEmpty)
                    {
                        envConfig = JObject.Parse("{}");
                    }
                }
            }
            var config = LoadConfig(path, createEmpty);

            if (envConfig != null && config != null)
            {
                config.Merge(envConfig);
            }
            if (config == null && envConfig != null)
            {
                config = envConfig;
            }

            return(config);
        }
예제 #4
0
    void Start()
    {
        Global = this;

        craftingRecipes = Resources.LoadAll <CraftingRecipes>("ScriptableObjects/CraftingRecipes");
        nodes           = nodeRoot.GetComponentsInChildren <Slot>();
    }
예제 #5
0
        static ContainerStores()
        {
            try
            {
                GlobalContainer = ((IServiceCollection) new ServiceCollection())
                                  .AddQwackLogging()
                                  .AddCalendarsFromJson(GetCalendarFilename())
                                  .AddFutureSettingsFromJson(GetFutureSettingsFile())
                                  .AddCurrenciesFromJson(GetCurrenciesFilename())
                                  .AddSingleton(typeof(IObjectStore <>), typeof(ExcelObjectStore <>))
                                  .BuildServiceProvider();

                SessionContainer = GlobalContainer.CreateScope().ServiceProvider;

                SessionContainer.GetRequiredService <IFutureSettingsProvider>();

                PnLAttributor = new PnLAttributor();
            }
            catch (Exception ex)
            {
                if (Directory.Exists(@"C:\Temp"))
                {
                    File.WriteAllText($@"C:\Temp\QwackInitializationError_{DateTime.Now:yyyyMMdd_HHmmss}.txt", ex.ToString());
                }
            }
        }
        public void Configuration(IAppBuilder app)
        {
            InitialzieContainer();
            InitializeEFConfiguration();
            var env = GlobalContainer.GetService <IApplicationEnvironment>();

            if (env.IsProduction())
            {
                GlobalContainer.AddSingleton(typeof(ISuitablePathResolver), typeof(MinimizedPathResolver));
            }

            if (!IsWindowsAuthentication())
            {
                Authentication.ConfigureAuth(app);
            }

            UseRedirectWhenDirectAccess(app);

            app.UseCors(CorsOptions.AllowAll);

            app.UseServiceUnit(
                ServiceUnitSettings.Create().SetContextCreatedHandler(OnServiceUnitContextCreated),
                new ServiceUnitApi(),
                new ServiceUnitForm(),
                new ServiceUnitResource()
            {
                JavaScriptFormatter = (text, culture, resourceName) =>
                {
                    return(";(function(){ App.culture(\"" + culture.Name +
                           "\",{ \"text\": { " + resourceName + ":" + text + "}} );})();");
                }
            });

            UseDefaultPage(app);
        }
        public void Init()
        {
            var container = new GlobalContainer();

            container.ExecuteInstaller(new AutoInstaller(GetType().Assembly));
            _container = container;
        }
예제 #8
0
        /// <summary>Creates an entity controller instance</summary>
        /// <param name="controllerId">Controller identifier</param>
        /// <param name="settings">Controller configuration</param>
        /// <param name="target">Controller target</param>
        /// <returns>The created IGame instance</returns>
        public virtual IController Create(string controllerId, IConfig settings, IControllerTarget target)
        {
#if DEBUG
            if (!this.constructors.ContainsKey(controllerId))
            {
                throw new ArgumentOutOfRangeException(
                          "controllerConfig", "No controller found with id '{0}'.".FormatInvariant(controllerId));
            }
#endif

            var ctor = this.constructors[controllerId];

            //// Log.Trace("Creating controller '{0}' ({1}) with target '{2}'\nSettings: {3}", controllerId, ctor.DeclaringType.FullName, target.Id, settings);

            var defaultParameters = new Dictionary <Type, object>
            {
                { typeof(IResourceLibrary), this.resources },
                { typeof(TControllerTarget), target },
                { typeof(IConfig), settings },
            };
            var parameters = ctor.GetParameters().Select(p => p.ParameterType)
                             .Select(t =>
                                     defaultParameters.ContainsKey(t)  ? defaultParameters[t] :
                                     t.IsArray ? GlobalContainer.ResolveAll(t) :
                                     GlobalContainer.Resolve(t))
                             .ToArray();

            var controller = (IController)ctor.Invoke(parameters);
            this.controllerManager.AddController(controller);
            return(controller);
        }
예제 #9
0
        /// <summary>Called when behaviour instance is being loaded</summary>
        public void Awake()
        {
            // Set the singleton instance
            if (GameBehaviour.Instance != null)
            {
                throw new InvalidOperationException("Only one instance of GameBehaviour is allowed per scene");
            }

            GameBehaviour.Instance = this;

            // Resolve the asset loaders
            ResourceManager.RegisterResourceLoaders(GlobalContainer.ResolveAll <IResourceLoader>());

            // Register the resource library singleton
            var resources = ResourceLibrary.FromString(this.ResourceLibraryXml.text);

            new DependencyContainer().RegisterSingleton <IResourceLibrary>(resources);

            // Create the IGame instance
            var gameDefinition = resources.GetSerializedResource <GameDefinition>(this.GameDefinitionId);

            this.game = (UnityGame)GlobalContainer.Resolve <IGameFactory>().Create(gameDefinition);

            //// Log.Trace("Loaded game '{0}' with {1} levels:\n{2}", this.game.Title, this.game.Levels.Length, string.Join("\n", this.game.Levels.Select(l => "{0} ({1})".FormatInvariant(l.Title, l.Id)).ToArray()));

            //// TODO: Drive level loading from a menu system
            // Load the first level
            var firstLevel = this.game.Levels.First().Id;

            Log.Trace("Loading level '{0}'...", firstLevel);
            this.game.LoadLevel(firstLevel);
        }
예제 #10
0
        protected void Application_Start(object sender, EventArgs e)
        {
            //Create global logger name
            var appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);

            this.LoggerName = appName + "Logger";

            //Create logging ability for this class
            LoggableClass = new LoggableClassInstance(this.LoggerName, "Global.asax.cs");

            //Configure IoC
            GlobalContainer = ConfigureIoC();
            GlobalConfiguration.Configuration.DependencyResolver = new DependencyResolverUnity(GlobalContainer); //allow IoC container to resolve all dependencies

            //Register a filter provider that works with Unity.
            //This step is necessary to get the property injection working in our AuthorizationAttribute class for the UserService.
            //See this: http://stackoverflow.com/questions/19130441/cant-inject-on-system-web-http-filters-actionfilterattribute-using-unity-bootst
            RegisterFilterProviders(GlobalContainer);

            //Get handlers and filters
            var corsHandler   = GlobalContainer.Resolve <CorsMessageHandler>(); //handles CORS requests
            var authAttribute = GlobalContainer.Resolve <AuthorizationAttribute>();
            var logAttribute  = GlobalContainer.Resolve <LogAttribute>();       //enables logging controller method exceptions

            WebApiConfig.Register(GlobalConfiguration.Configuration, corsHandler, authAttribute, logAttribute);

            //Populate the InsPlans and Icd9Codes tables on a specific time interval
            populateIcd9CodesTableCallback = new TimerCallback(PopulateIcd9CodesTable);
            populateIcd9CodesTableTimer    = new Timer(populateIcd9CodesTableCallback, null, 1000, 300000); //start in one second and then run every five minutes

            populateInsPlansTableCallback = new TimerCallback(PopulateInsPlansTable);
            populateInsPlansTableTimer    = new Timer(populateInsPlansTableCallback, null, 1000, 300000); //start in one second and then run every five minutes
        }
예제 #11
0
        /// <summary>
        /// Will select the shell with the name in the configuration
        /// </summary>
        protected void SelectShell(IEnumerable <Assembly> assemblies, ModulesConfiguration modulesConfig)
        {
            Type selectedShell;
            var  shells = assemblies.SelectMany(ass => ass.GetTypes())
                          .Where(t => typeof(IModuleShell).IsAssignableFrom(t) && t.GetCustomAttribute <ModuleShellAttribute>() != null);

            if (string.IsNullOrEmpty(modulesConfig.Shell.ShellName))
            {
                selectedShell = shells.FirstOrDefault();
            }
            else
            {
                selectedShell = shells.FirstOrDefault(shellType =>
                                                      shellType.GetCustomAttribute <ModuleShellAttribute>().Name.Equals(modulesConfig.Shell.ShellName));
            }

            if (selectedShell == null)
            {
                var fallbackShell = (FallbackShellViewModel)GlobalContainer.Resolve <IModuleShell>(FallbackShellViewModel.ShellName);
                fallbackShell.RunMode         = Name;
                fallbackShell.ConfiguredShell = modulesConfig.Shell.ShellName;

                modulesConfig.Shell.ShellName = FallbackShellViewModel.ShellName;
                return;
            }

            var shellAttr = selectedShell.GetCustomAttribute <ModuleShellAttribute>();

            modulesConfig.Shell.ShellName = shellAttr.Name;
        }
예제 #12
0
 void Awake()
 {
     Global        = this;
     inputManager  = GetComponent <InputManager>();
     possesor      = GetComponent <Possesor>();
     screenManager = FindObjectOfType <ScreenManager>();
     captureCam    = FindObjectOfType <CameraController>().GetComponentInChildren <Camera>();
 }
예제 #13
0
 /// <summary>
 /// Container を初期化します
 /// </summary>
 private void InitialzieContainer()
 {
     GlobalContainer.Initialize(new NinjectContainer());
     GlobalContainer.AddInstance(typeof(IApplicationEnvironment),
                                 new WebApplicationEnvironment(GetEnvironmentName()));
     GlobalContainer.AddInstance(typeof(ITypePath),
                                 new AutoDetectTypePath(typeof(Startup).Namespace, Assembly.GetExecutingAssembly()));
     GlobalContainer.AddInstance(typeof(IMailSenderFactory), new SmtpMailSenderFactory());
 }
예제 #14
0
        public static HttpResponseMessage CreateFileDownloadErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string detail)
        {
            HttpResponseMessage response = request.CreateResponse(statusCode);
            var env = GlobalContainer.GetService <IApplicationEnvironment>();
            var uri = env.ApplicationRoot + "/Shared/V1/Users/page/DownloadError?Message=" + message + "&Detail=" + detail;

            response.Headers.Location = new Uri(uri, UriKind.RelativeOrAbsolute);
            return(response);
        }
예제 #15
0
        static ContainerStores()
        {
            GlobalContainer = ((IServiceCollection) new ServiceCollection())
                              .AddQwackLogging()
                              .AddCalendarsFromJson(GetCalendarFilename())
                              .BuildServiceProvider();

            _sessionContainer = GlobalContainer.CreateScope().ServiceProvider;
        }
예제 #16
0
    private void Awake()
    {
        _transform        = transform;
        _gameEventManager = GameEventManager.Instance;
        _spellManager     = SpellManager.Instance;
        _globalContainer  = GlobalContainer.Instance;

        _gameEventManager.onShootPress += context => OnShootPress(context);
    }
예제 #17
0
        public static void Reset()
        {
            //Reset(GlobalContainer);

            if (GlobalContainer != null)
            {
                GlobalContainer.Dispose();
                GlobalContainer = null;
            }
        }
예제 #18
0
        public void ResolveUsingGlobalContainer()
        {
            new DependencyContainer()
            .RegisterType <ITestTypeA, TestTypeA1>();

            var instance = GlobalContainer.Resolve <ITestTypeA>();

            Assert.IsNotNull(instance);
            Assert.IsInstanceOf <TestTypeA1>(instance);
        }
예제 #19
0
파일: Startup.cs 프로젝트: shinch4n/iCare
        private void InitializeAuthentication()
        {
            var auth = new ApplicationAuthentication();

            var context = new ICIdentityDbContext(ConnectionFactory.Create(ConnectionFactory.GetConnectionString(typeof(ICIdentityDbContext).Name)));

            auth.AddProviders(new AspNetIdentityAuthenticationProvider(DefaultUserManager.Create(new UserStore <IdentityUser>(context))));

            GlobalContainer.AddInstance(auth);
        }
예제 #20
0
        private void TestResolve <T>()
        {
            // Assert
            var container = new GlobalContainer();

            // Act
            var obj = container.Resolve <T>();

            // Assert
            Assert.IsNotNull(obj);
        }
예제 #21
0
        public static string ResolveSuitableFileUrl(this Control source, string path)
        {
            var resolvedPath = source.ResolveUrl(path);
            var resolver     = GlobalContainer.GetService <ISuitablePathResolver>();

            if (resolver == null)
            {
                return(resolvedPath);
            }
            return(resolver.Resolve(resolvedPath));
        }
예제 #22
0
        public FileOutputMailSender(SmtpMailConfiguration smtpConfig)
        {
            Contract.NotNull(smtpConfig, "smtpConfig");
            Contract.NotNull(smtpConfig.FileOutputDir, "FileOutputDir");

            outputDirectory = GlobalContainer.GetService <IApplicationEnvironment>().MapPath(smtpConfig.FileOutputDir);
            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }
            this.smtpConfig = smtpConfig;
        }
예제 #23
0
    private void Awake()
    {
        _gameEventManager = GameEventManager.Instance;
        _sceneLoader      = SceneLoader.Instance;
        _audioManager     = AudioManager.Instance;
        _mapGenerator     = MapGenerator.Instance;
        _mobGenerator     = MobGenerator.Instance;
        _globalContainer  = GlobalContainer.Instance;

        _gameEventManager.onGatewayEnter += OnGatewayEnter;
        _gameEventManager.onPlayerDeath  += OnPlayerDeath;
    }
예제 #24
0
        public void CreateGame()
        {
            var gameDefinition = this.resourceLibrary.GetSerializedResource <GameDefinition>(this.gameDefinitionId);
            var game           = GlobalContainer.Resolve <IGameFactory>().Create(gameDefinition);

            Assert.IsInstanceOf <UnityGame>(game);

            game.LoadLevel(game.Levels.First().Id);

            var allResources = string.Join("\r\n", this.resourceLibrary.GetAllResources <IResource>().Select(resource => resource.ToString()).ToArray());

            Assert.IsNotNull(allResources);
        }
예제 #25
0
        public void ResolveAllUsingGlobalContainer()
        {
            new DependencyContainer()
            .RegisterType <ITestTypeA, TestTypeA1>("One");
            new DependencyContainer()
            .RegisterType <ITestTypeA, TestTypeA2>("Two");

            var instances = GlobalContainer.ResolveAll <ITestTypeA>();

            Assert.IsNotNull(instances);
            Assert.AreEqual(2, instances.Count());
            Assert.IsTrue(new[] { typeof(TestTypeA1), typeof(TestTypeA2) }
                          .All(t => instances.Any(i => i.GetType() == t)));
        }
예제 #26
0
        public void ResolveRegisteredLoaders()
        {
            var loaders = GlobalContainer.ResolveAll <IResourceLoader>();

            Assert.AreEqual(2, loaders.Count());

            var textAssetLoader = GlobalContainer.Resolve <IResourceLoader>("Unity TextAsset Loader");

            Assert.IsInstanceOf <TextAssetResourceLoader>(textAssetLoader);

            var prefabLoader = GlobalContainer.Resolve <IResourceLoader>("Unity Prefab Loader");

            Assert.IsInstanceOf <PrefabAssetResourceLoader>(prefabLoader);
        }
        private JObject LoadConfig(string path, bool createEmpty = true)
        {
            //HostingEnvironment
            var dir            = GlobalContainer.GetService <IApplicationEnvironment>().MapPath(path);
            var configFileName = System.IO.Path.Combine(dir, ConfigFileName);

            if (File.Exists(configFileName))
            {
                return(JObject.Parse(File.ReadAllText(configFileName)));
            }
            if (createEmpty)
            {
                return(JObject.Parse("{}"));
            }
            return(null);
        }
예제 #28
0
        public void RealizeWithArrayParameterConstructor()
        {
            new DependencyContainer()
            .RegisterType <ITestTypeA, TestTypeA1>("one")
            .RegisterType <ITestTypeA, TestTypeA2>("two")
            .RegisterType <TestTypeB, TestTypeB>();

            var instance = GlobalContainer.Resolve <TestTypeB>();

            Assert.IsNotNull(instance);
            Assert.IsNotNull(instance.A1);
            Assert.IsInstanceOf <TestTypeA1>(instance.A1);
            Assert.IsNotNull(instance.As);
            Assert.AreEqual(2, instance.As.Length);
            Assert.IsInstanceOf <TestTypeA1>(instance.As[0]);
            Assert.IsInstanceOf <TestTypeA2>(instance.As[1]);
        }
        void IMiddlewareRegisterSetting.Use(global::Owin.IAppBuilder builder)
        {
            ITypePath           typePath = GlobalContainer.GetService <ITypePath>();
            List <TypePathItem> items    = typePath.Items.Where(i => i.TargetType.IsSubclassOf(typeof(ServiceUnitPersistentConnection))).ToList();

            foreach (TypePathItem item in items)
            {
                PathMapResult pathconvert = PathMapper.Convert(
                    item.Path,
                    "/{ServiceUnitName}/{Version}/{Role}/Socket/{Name}Socket",
                    "/{ServiceUnitName}/{Version}/{Role}/socket/{Name}");
                if (pathconvert.Success)
                {
                    builder.MapSignalR(pathconvert.MappedPath, item.TargetType, new ConnectionConfiguration());
                }
            }
        }
예제 #30
0
        public void ResolveRegisteredLoggers()
        {
            var loggers = GlobalContainer.ResolveAll <ILogger>();

            Assert.AreEqual(1, loggers.Count());

            var loggerA = loggers.Single();

            Assert.IsInstanceOf <Core.GenericAsyncLogger <Core.Unity.DebugConsoleLogger> >(loggerA);

            var loggerB = GlobalContainer.Resolve <ILogger>();

            Assert.AreSame(loggerA, loggerB);

            var loggerC = GlobalContainer.Resolve <ILogger>("Unity Async Debug Logger");

            Assert.AreSame(loggerB, loggerC);
        }