Ejemplo n.º 1
0
        private void ConfigureWebApi(IAppBuilder app, IResolutionRoot resolutionRoot)
        {
            var config = new HttpConfiguration();

            var kernel = new ChildKernel(resolutionRoot);

            kernel.Rebind <HttpConfiguration>().ToConstant(config);
            kernel.Bind <DefaultModelValidatorProviders>().ToConstant(new DefaultModelValidatorProviders(config.Services.GetServices(typeof(ModelValidatorProvider)).Cast <ModelValidatorProvider>()));
            kernel.Bind <DefaultFilterProviders>().ToConstant(new DefaultFilterProviders(config.Services.GetServices(typeof(IFilterProvider)).Cast <IFilterProvider>()));

            var dependencyResolver = new NinjectDependencyResolver(kernel);

            config.DependencyResolver = dependencyResolver;

            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.EnableCors(new EnableCorsAttribute("http://localhost:8081", "*", "*", "Cookie")
            {
                SupportsCredentials = true
            });

            var constraintResolver = new DefaultInlineConstraintResolver();

            constraintResolver.ConstraintMap.Add("situation", typeof(SituationConstraint));

            config.MapHttpAttributeRoutes(constraintResolver);

            config.Routes.MapHttpRoute("Default", "{controller}/{id}");

            config.EnableSwagger(c =>
            {
                var baseDirectory    = AppDomain.CurrentDomain.BaseDirectory;
                var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
                var commentsFile     = Path.Combine(baseDirectory, "bin", commentsFileName);

                c.IncludeXmlComments(commentsFile);
                c.RootUrl(h => $"{h.RequestUri.Scheme}://{h.RequestUri.Host}:{h.RequestUri.Port}/api");
                c.SingleApiVersion("v1", "Michael's Place SPA API.");
            })
            .EnableSwaggerUi();

            app.Map("/api", webApi =>
            {
                webApi.UseWebApi(config);
            });
        }
        public static void CanChildRedefineRepositoryInChildWithoutAffectingParent()
        {
            /*
             * Define repository & BL in the parent kernel.
             * Redefine in the child.
             */

            //Arrange
            var kernel = new StandardKernel();

            kernel.Bind <IMyRepository>().To <MyRepository>().InTransientScope();
            kernel.Bind <IMyBusinessLogic>().To <MyBusinessLogic>().InTransientScope();

            var myRepository = new Mock <IMyRepository>();

            myRepository.Setup(x => x.Get("Test")).Returns("I came from a mock");

            var childKernel = new ChildKernel(kernel);

            childKernel.Bind <IMyRepository>().ToConstant(myRepository.Object).InTransientScope();

            //Act
            var myBusinessLogicFromTheChild  = childKernel.Get <IMyBusinessLogic>();
            var myBusinessLogicFromTheParent = kernel.Get <IMyBusinessLogic>();

            //Assert

            Assert.Equal("I came from a mock and then the business layer returned it.",
                         myBusinessLogicFromTheChild.DoSomething("Test"));

            Assert.Equal("You got: Test from myRepository and then the business layer returned it.",
                         myBusinessLogicFromTheParent.DoSomething("Test"));
        }
        public static void CanChildSupplyRepositoryInstanceToParent()
        {
            /*
             * Repository in the child kernel.
             * Business Logic in the parent kernel.
             * We expect Ninject to construct the BL in the parent with the child kernels
             * repository
             */

            //Arrange
            var kernel = new StandardKernel();

            kernel.Bind <IMyBusinessLogic>().To <MyBusinessLogic>().InTransientScope();

            var myRepository = new Mock <IMyRepository>();

            myRepository.Setup(x => x.Get("Test")).Returns("I came from a mock");

            var childKernel = new ChildKernel(kernel);

            childKernel.Bind <IMyRepository>().ToConstant(myRepository.Object).InSingletonScope();

            //Act
            var myBusinessLogic = childKernel.Get <IMyBusinessLogic>();

            //Assert
            Assert.Equal("I came from a mock and then the business layer returned it.",
                         myBusinessLogic.DoSomething("Test"));
        }
Ejemplo n.º 4
0
        private IHandlerBase ResolveCommand(Command Command, CommandDispatcher dispatcher, Type type)
        {
            var context = new ChildKernel(_kernel);

            // long-lived
            context.BindInstance(dispatcher);
            context.BindInstance(dispatcher.Environments);
            context.BindInstance(dispatcher.State);
            context.BindInstance(dispatcher.Output);
            context.BindInstance(dispatcher.Parser);
            context.BindInstance(dispatcher.Handlers);

            // transient
            context.BindInstance(Command);
            context.BindInstance(Command.Arguments);

            if (dispatcher.Environments.Current != null)
            {
                context.Bind(dispatcher.Environments.Current.GetType()).ToConstant(dispatcher.Environments.Current);
            }

            var instance = context.Get(type);

            context.Dispose();
            return(instance as IHandlerBase);
        }
Ejemplo n.º 5
0
        public static void CanWhenTakePrecidenceForBusinessLogicWhenUsedWithChildKernel()
        {
            //Arrange
            var kernel = new StandardKernel();

            kernel.Bind <IMyRepository>().To <MyRepository>().InTransientScope();
            kernel.Bind <IMyBusinessLogic>().To <MyBusinessLogic>().InTransientScope();

            var myRepository = new Mock <IMyRepository>();

            myRepository.Setup(x => x.Get("Test")).Returns("I came from a mock");

            var shouldReturnTestInstance = new ByValueBooleanWrapper(true);

            var childKernel = new ChildKernel(kernel);

            childKernel.Bind <IMyRepository>().ToConstant(myRepository.Object).When(x => shouldReturnTestInstance.Flag);

            //Act
            var myBusinessLogic = childKernel.Get <IMyBusinessLogic>();

            //Assert
            Assert.Equal("I came from a mock and then the business layer returned it.",
                         myBusinessLogic.DoSomething("Test"));

            shouldReturnTestInstance.Flag = false;

            myBusinessLogic = kernel.Get <IMyBusinessLogic>();

            Assert.Equal("You got: Test from myRepository and then the business layer returned it.",
                         myBusinessLogic.DoSomething("Test"));
        }
        public static void CanSecondChildSupplyDifferentInstanceOfBusinessLogicWithCorrectRepository()
        {
            /*
             * Repository in the child kernel.
             * Business Logic in the parent kernel.
             * Dispose the child kernel and try it again!
             */

            //Arrange
            var kernel = new StandardKernel();

            kernel.Bind <IMyRepository>().To <MyRepository>();
            kernel.Bind <IMyBusinessLogic>().To <MyBusinessLogic>().InTransientScope();

            var myRepository1 = new Mock <IMyRepository>();

            myRepository1.Setup(x => x.Get("Test")).Returns("I came from a mock");

            var childKernel1 = new ChildKernel(kernel);

            childKernel1.Bind <IMyRepository>().ToConstant(myRepository1.Object).InSingletonScope();

            var businessLogic1 = childKernel1.Get <IMyBusinessLogic>();

            childKernel1.Dispose();

            var myRepository2 = new Mock <IMyRepository>();

            myRepository2.Setup(x => x.Get("Test")).Returns("I came from a mock2");

            var childKernel2 = new ChildKernel(kernel);

            childKernel1.Bind <IMyRepository>().ToConstant(myRepository2.Object).InSingletonScope();

            //Act
            var businessLogic2 = childKernel2.Get <IMyBusinessLogic>();

            //Assert
            Assert.NotEqual(businessLogic1, businessLogic2);

            Assert.Equal("I came from a mock and then the business layer returned it.",
                         businessLogic1.DoSomething("Test"));

            Assert.Equal("I came from a mock and then the business layer returned it.",
                         businessLogic2.DoSomething("Test"));
        }
Ejemplo n.º 7
0
        private IChildKernel GetChildKernelWithBindings(IKernel kernel)
        {
            IChildKernel childKernel = new ChildKernel(kernel);

            childKernel.Bind <IVasaClient>().ToMethod(config =>
            {
                return(new VasaClient());
            });

            return(childKernel);
        }
Ejemplo n.º 8
0
        public void ChildKernel_IFooBoundInChildKernel_ParentKernelCannotResolveIFoo()
        {
            // Assemble
            var parentKernel = new StandardKernel();

            var childKernel = new ChildKernel(parentKernel);

            childKernel.Bind <IFoo>().To <Foo>();

            // Act
            Assert.Throws <ActivationException>(() => parentKernel.Get <IFoo>());
        }
Ejemplo n.º 9
0
        public SimpleBootstrapper(IResolutionRoot resolutionRoot, ILogger logger)
            : base(resolutionRoot, logger)
        {
            var nexus = new ChildKernel(ResolutionRoot, new NexusServerModule());

            _account = new ChildKernel(nexus, new AccountServerModule());
            _auth    = CreateAuthKernel(nexus);
            _world   = new ChildKernel(nexus, new WorldServerModule());
            _channel = new ChildKernel(_world, new ServerModule(), new ChannelServerModule());

            // HACK :(
            nexus.Bind <IAccountService>().ToMethod(ctx => _account.Get <IAccountService>());
        }
Ejemplo n.º 10
0
        public void TestReferenceFromParent()
        {
            StandardKernel kernel = new StandardKernel();
            ChildKernel    child  = new ChildKernel(kernel);

            kernel.Bind <IBaseClass, ClassA>().To <ClassA>();
            child.Bind <IBaseClass, ClassD_A>().To <ClassD_A>();

            var classD_A = child.Get <ClassD_A>();

            Assert.IsNotNull(classD_A);

            Assert.AreEqual("Class A: Class D", classD_A.Message);
        }
Ejemplo n.º 11
0
        public void Foo()
        {
            var kernel = new StandardKernel();

            kernel.Bind <IServiceProvider>().ToMethod(GetServiceProvider);
            kernel.Bind <IService>().To <RootService>();

            var childKernel = new ChildKernel(kernel);

            childKernel.Bind <IService>().To <ChildService>();

            kernel.Get <IServiceProvider>().Provide().Should().BeOfType <RootService>();
            childKernel.Get <IServiceProvider>().Provide().Should().BeOfType <ChildService>();
        }
Ejemplo n.º 12
0
        public void ChildkernelChangedBinding()
        {
            var pluginAKernel = new ChildKernel(this.kernel);

            pluginAKernel.Load(new BarracksModule());

            var pluginBKernel = new ChildKernel(this.kernel);

            pluginBKernel.Bind <IWeapon>().To <Dagger>().WhenInjectedExactlyInto <Samurai>();

            var pluginASamurai = pluginAKernel.Get <Samurai>();
            var pluginBSamurai = pluginBKernel.Get <Samurai>();

            pluginASamurai.Weapon.Should().NotBeSameAs(pluginBSamurai.Weapon);
        }
Ejemplo n.º 13
0
        public void TestMultipleNestingChild()
        {
            StandardKernel kernel = new StandardKernel();
            ChildKernel    child1 = new ChildKernel(kernel);
            ChildKernel    child2 = new ChildKernel(child1);

            kernel.Bind <ClassA>().ToSelf();
            child2.Bind <ClassD_A>().ToSelf();

            var classD_A = child2.Get <ClassD_A>();

            Assert.IsNotNull(classD_A);

            Assert.AreEqual("Class A: Class D", classD_A.Message);
        }
Ejemplo n.º 14
0
        public void TestOneChildGetParent()
        {
            StandardKernel kernel = new StandardKernel();
            ChildKernel    child  = new ChildKernel(kernel);

            kernel.Bind <IBaseClass>().To <ClassA>();

            child.Bind <IBaseClass>().To <ClassB>();

            var classesFromParent = kernel.GetAll <IBaseClass>();

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

            var classesFromChild = child.GetAll <IBaseClass>();

            Assert.AreEqual(1, classesFromChild.Count());
        }
Ejemplo n.º 15
0
        public void ChildKernel_IFooBoundInParentAndChildKernel_ParentCanResolveIFoo()
        {
            // Assemble
            var parentKernel = new StandardKernel();

            parentKernel.Bind <IFoo>().To <Foo1>();

            var childKernel = new ChildKernel(parentKernel);

            childKernel.Bind <IFoo>().To <Foo2>();

            // Act
            var foo = parentKernel.Get <IFoo>();

            // Act
            Assert.IsInstanceOf <Foo1>(foo);
        }
Ejemplo n.º 16
0
        public void ChildKernel_SameInterfaceBoundInTwoChildKernels_EachKernelResolvesInstanceCorrectly()
        {
            // Assemble
            var parentKernel = new StandardKernel();

            parentKernel.Bind <IBar>().To <Bar>();

            var barNoneKernel = new ChildKernel(parentKernel);

            barNoneKernel.Bind <IFoo>().To <Foo>();

            var allTheBarsKernel = new ChildKernel(parentKernel);

            allTheBarsKernel.Bind <IFoo>().To <FooDependingOnBar>();

            // Act
            var barNone = barNoneKernel.Get <IFoo>();
            var bars    = allTheBarsKernel.Get <IFoo>();

            // Assert

            Assert.IsInstanceOf <Foo>(barNone);
            Assert.IsInstanceOf <FooDependingOnBar>(bars);
        }
Ejemplo n.º 17
0
        public IEngine Create(IReadOnlyCollection <EntityData> snapshot, IReadOnlyCollection <EntityTemplate> templates)
        {
            _logger.Info("Creating new RuntimeEngine instance");

            // Create a child kernel for this new instance.
            var k = new ChildKernel(_kernel, new NinjectSettings
            {
                InjectNonPublic = true
            });

            k.Load(_kernel.GetAll <IEngineModule>());
            k.Bind <IEntityTemplateProvider>().ToConstant(new RuntimeEntityTemplateProvider(templates));

            IList <EngineEntity> existingEntities = new List <EngineEntity>();

            foreach (var entity in snapshot)
            {
                existingEntities.Add(new EngineEntity(entity.Id, entity.Components, k.Get <IEventDispatcher>()));
            }

            k.Get <IEntityService>(new ConstructorArgument("entities", existingEntities));

            return(k.Get <IEngine>());
        }
Ejemplo n.º 18
0
        public int Run()
        {
            LOG.Info("Starting server");
            TimedReferenceController.SetMode(CacheType.PERMANENT);

            if (Config.Services == null)
            {
                LOG.Warn("No services found in the configuration file, exiting");
                return(1);
            }

            if (!Directory.Exists(Config.GameLocation))
            {
                LOG.Fatal("The directory specified as gameLocation in config.json does not exist");
                return(1);
            }

            Directory.CreateDirectory(Config.SimNFS);
            Directory.CreateDirectory(Path.Combine(Config.SimNFS, "Lots/"));
            Directory.CreateDirectory(Path.Combine(Config.SimNFS, "Objects/"));

            Content.Model.AbstractTextureRef.ImageFetchFunction = Utils.SoftwareImageLoader.SoftImageFetch;

            //TODO: Some content preloading
            LOG.Info("Scanning content");
            Content.Content.Init(Config.GameLocation, Content.ContentMode.SERVER);
            Kernel.Bind <Content.Content>().ToConstant(Content.Content.Get());
            VMContext.InitVMConfig();
            Kernel.Bind <MemoryCache>().ToConstant(new MemoryCache("fso_server"));

            LOG.Info("Loading domain logic");
            Kernel.Load <ServerDomainModule>();

            Servers     = new List <AbstractServer>();
            CityServers = new List <CityServer>();
            Kernel.Bind <IServerNFSProvider>().ToConstant(new ServerNFSProvider(Config.SimNFS));

            if (Config.Services.UserApi != null &&
                Config.Services.UserApi.Enabled)
            {
                var childKernel = new ChildKernel(
                    Kernel
                    );
                var api = new UserApi(Config, childKernel);
                ActiveUApiServer = api;
                Servers.Add(api);
                api.OnRequestShutdown       += RequestedShutdown;
                api.OnBroadcastMessage      += BroadcastMessage;
                api.OnRequestUserDisconnect += RequestedUserDisconnect;
                api.OnRequestMailNotify     += RequestedMailNotify;
            }

            foreach (var cityServer in Config.Services.Cities)
            {
                /**
                 * Need to create a kernel for each city server as there is some data they do not share
                 */
                var childKernel = new ChildKernel(
                    Kernel,
                    new ShardDataServiceModule(Config.SimNFS),
                    new CityServerModule()
                    );

                var city = childKernel.Get <CityServer>(new ConstructorArgument("config", cityServer));
                CityServers.Add(city);
                Servers.Add(city);
            }

            foreach (var lotServer in Config.Services.Lots)
            {
                if (lotServer.SimNFS == null)
                {
                    lotServer.SimNFS = Config.SimNFS;
                }
                var childKernel = new ChildKernel(
                    Kernel,
                    new LotServerModule()
                    );

                Servers.Add(
                    childKernel.Get <LotServer>(new ConstructorArgument("config", lotServer))
                    );
            }

            if (Config.Services.Tasks != null &&
                Config.Services.Tasks.Enabled)
            {
                var childKernel = new ChildKernel(
                    Kernel,
                    new TaskEngineModule()
                    );

                childKernel.Bind <TaskServerConfiguration>().ToConstant(Config.Services.Tasks);
                childKernel.Bind <TaskTuning>().ToConstant(Config.Services.Tasks.Tuning);

                var tasks = childKernel.Get <TaskServer>(new ConstructorArgument("config", Config.Services.Tasks));
                Servers.Add(tasks);
                ActiveTaskServer = tasks;
                Server.Servers.Tasks.Domain.ShutdownTask.ShutdownHook = RequestedShutdown;
            }

            foreach (var server in Servers)
            {
                server.OnInternalShutdown += ServerInternalShutdown;
            }

            Running = true;

            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
            AppDomain.CurrentDomain.ProcessExit  += CurrentDomain_ProcessExit;

            /*
             * NetworkDebugger debugInterface = null;
             *
             * if (Options.Debug)
             * {
             *  debugInterface = new NetworkDebugger(Kernel);
             *  foreach (AbstractServer server in Servers)
             *  {
             *      server.AttachDebugger(debugInterface);
             *  }
             * }
             */

            LOG.Info("Starting services");
            foreach (AbstractServer server in Servers)
            {
                server.Start();
            }

            HostPool.Start();

            //Hacky reference to maek sure the assembly is included
            FSO.Common.DatabaseService.Model.LoadAvatarByIDRequest x;

            /*if (debugInterface != null)
             * {
             *  Application.EnableVisualStyles();
             *  Application.Run(debugInterface);
             * }
             * else*/
            {
                while (Running)
                {
                    Thread.Sleep(1000);
                    lock (Servers)
                    {
                        if (Servers.Count == 0)
                        {
                            LOG.Info("All servers shut down, shutting down program...");

                            Kernel.Get <IGluonHostPool>().Stop();

                            /*var domain = AppDomain.CreateDomain("RebootApp");
                             *
                             * var assembly = "FSO.Server.Updater, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
                             * var type = "FSO.Server.Updater.Program";
                             *
                             * var updater = typeof(FSO.Server.Updater.Program);
                             *
                             * domain.CreateInstance(assembly, type);
                             * AppDomain.Unload(AppDomain.CurrentDomain);*/
                            return(2 + (int)ShutdownMode);
                        }
                    }
                }
            }
            return(1);
        }
Ejemplo n.º 19
0
        public IContext CreateDeviceInContext(Settings.IProvider settingsProvider, Messaging.Client.IEndpoint clientEndpoint)
        {
            ChildKernel kernel = new ChildKernel(_kernel);

            kernel.Bind <Command.Response.IBuilder>().To <Command.Response.Builder.VersionResponse>().InSingletonScope();
            kernel.Bind <Command.Response.IBuilder>().To <Command.Response.Builder.RostaResponse>().InSingletonScope();
            kernel.Bind <Command.Response.IBuilder>().To <Command.Response.Builder.DeviceResponse>().InSingletonScope();
            kernel.Bind <Command.Response.IBuilder>().To <Command.Response.Builder.UdpResponse>().InSingletonScope();
            kernel.Bind <Command.Response.IBuilder>().To <Command.Response.Builder.SaveResponse>().InSingletonScope();
            kernel.Bind <Command.Response.IParser>().To <Command.Response.Parser>().InSingletonScope();
            kernel.Bind <Command.Endpoint.IFactory>().To <Command.Endpoint.Factory>().InSingletonScope();

            kernel.Bind <Packet.IParser>().To <Packet.Parser>().InSingletonScope();
            kernel.Bind <Packet.Endpoint.IFactory>().To <Packet.Endpoint.Factory>().InSingletonScope();

            kernel.Bind <Event.IMediator>().To <Event.Mediator>().InSingletonScope();
            kernel.Bind <State.Event.IFactory>().To <State.Event.Factory>().InSingletonScope();
            kernel.Bind <State.Context.IFactory>().To <State.Context.Factory>().InSingletonScope();

            kernel.Bind <State.ITransition>().To <State.Transition>().InSingletonScope();
            kernel.Bind <State.IFactory>().To <State.Factory>().InSingletonScope();
            kernel.Bind <State.IMachine>().To <State.Machine>().InSingletonScope();

            kernel.Bind <Entity.IFactory>().To <Entity.Factory>().InSingletonScope();

            kernel.Bind <Entity.Observable.IFactory>().To <Entity.Observable.CurrentElectricityConsumptionFactory>().InSingletonScope();
            kernel.Bind <Entity.Observable.IAbstractFactory>().To <Entity.Observable.AbstractFactory>().InSingletonScope();

            kernel.Bind <IBridge>().To <Bridge>().InSingletonScope();
            kernel.Bind <IInstance>().To <Instance>().InSingletonScope();
            kernel.Bind <IContext>().To <Context>().InSingletonScope();

            kernel.Bind <Settings.IProvider>().ToConstant(settingsProvider);
            kernel.Bind <Messaging.Client.IEndpoint>().ToConstant(clientEndpoint);

            return(kernel.Get <IContext>());
        }
Ejemplo n.º 20
0
        public Constructor GetNew()
        {
            var container = new ChildKernel(parentContainer);

            container.Bind <IModeSettings>().To <ModeSettings>().InSingletonScope();

            container.Bind <Map>().ToSelf().InSingletonScope();

            container.Bind(x =>
                           x.From(Assembly.GetAssembly(typeof(IGameMode))).SelectAllClasses().InheritedFrom <IGameMode>()
                           .BindAllInterfaces());

            container.Bind <ModeSettings>()
            .ToSelf()
            .InSingletonScope()
            .WithConstructorArgument("modes", container.GetAll <IGameMode>().ToArray());
            container.Bind <GameState>().ToSelf().InSingletonScope()
            .WithConstructorArgument("shift", container.Get <KeySettings>().Height);

            container.Bind <GameForm>().ToSelf().InSingletonScope();
            container.Bind <IMouseInput>().ToMethod(c => c.Kernel.Get <GameForm>()).InSingletonScope();
            container.Bind <IKeyInput>().ToMethod(c => c.Kernel.Get <GameForm>()).InSingletonScope();
            container.Bind <VisualizationSettings>().ToSelf().InSingletonScope();
            container.Bind <KeyBoardSettings>().ToSelf().InSingletonScope();
            container.Bind(x =>
                           x.From(Assembly.GetAssembly(typeof(IInputControl))).SelectAllClasses().InheritedFrom <IInputControl>()
                           .BindAllInterfaces());

            container.Bind <IInputControlSettings>().To <InputControlSettings>().InSingletonScope();
            container.Bind <InputControlSettings>()
            .ToSelf()
            .InSingletonScope()
            .WithConstructorArgument("controls", container.GetAll <IInputControl>().ToArray());

            container.Bind <Controller>().ToSelf().InSingletonScope();

            return(container.Get <Constructor>());
        }