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")); }
internal static IUiElementInformation GetUiElementInformation(classic.AutomationElement.AutomationElementInformation information) { try { var singleInfo = new ConstructorArgument("information", information); // 20140122 // IUiElementInformation adapterInformation = Kernel.Get<IUiElementInformation>(singleInfo); IUiElementInformation adapterInformation; // if (null != ChildKernel) { // adapterInformation = ChildKernel.Get<IUiElementInformation>(singleInfo); // var childKernel = GetChildKernel(); // adapterInformation = childKernel.Get<IUiElementInformation>(singleInfo); adapterInformation = ChildKernel.Get <IUiElementInformation>(singleInfo); // childKernel.Dispose(); // } else { // adapterInformation = Kernel.Get<IUiElementInformation>(singleInfo); // } return(adapterInformation); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Information"); // Console.WriteLine(eFailedToIssueInformation.Message); return(null); } }
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")); }
// internal static IUiEltCollection GetUiEltCollectionViaChildKerne(AutomationElementCollection elements, IChildKernel childKernel) // { // if (null == elements) { // return null; // } // try { // var manyElements = new ConstructorArgument("elements", elements); // IUiEltCollection adapterCollection = childKernel.Get<IUiEltCollection>("AutomationElementCollection.NET", manyElements); // return adapterCollection; // } // catch (Exception eFailedToIssueCollection) { // // TODO // // write error to error object!!! // // Console.WriteLine("Collection 01 via ChildKernel"); // // Console.WriteLine(eFailedToIssueCollection.Message); // return null; // } // } internal static IUiEltCollection GetUiEltCollection(classic.AutomationElementCollection elements) { if (null == elements) { return(null); } try { var manyElements = new ConstructorArgument("elements", elements); // 20140122 IUiEltCollection adapterCollection; // = Kernel.Get<IUiEltCollection>("AutomationElementCollection.NET", manyElements); // if (null != ChildKernel) { //Console.WriteLine("child coll"); // adapterCollection = ChildKernel.Get<IUiEltCollection>("AutomationElementCollection.NET", manyElements); // var childKernel = GetChildKernel(); // adapterCollection = childKernel.Get<IUiEltCollection>("AutomationElementCollection.NET", manyElements); adapterCollection = ChildKernel.Get <IUiEltCollection>("AutomationElementCollection.NET", manyElements); // childKernel.Dispose(); // } else { // adapterCollection = Kernel.Get<IUiEltCollection>("AutomationElementCollection.NET", manyElements); // } return(adapterCollection); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Collection 01"); // Console.WriteLine(eFailedToIssueCollection.Message); return(null); } }
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); }
public static void CanChildContainerRequestRepositoryFromParentContainer() { /* * Repository in the parent kernel. * Business Logic in the child kernel. * We expect Ninject to ask the parent kernel for the repository */ //Arrange var kernel = new StandardKernel(); var myRepository = new Mock <IMyRepository>(); myRepository.Setup(x => x.Get("Test")).Returns("I came from a mock"); kernel.Bind <IMyRepository>().ToConstant(myRepository.Object); var childKernel = new ChildKernel(kernel); kernel.Bind <IMyBusinessLogic>().To <MyBusinessLogic>(); //Act var myBusinessLogic = childKernel.Get <IMyBusinessLogic>(); //Assert Assert.Contains("I came from a mock and then the business layer returned it.", myBusinessLogic.DoSomething("Test")); }
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 IUiElement GetUiElementViaChildKernel(AutomationElement element, IChildKernel childKernel) // { // if (null == element) { // return null; // } // // try { // var singleElement = new ConstructorArgument("element", element); // IUiElement adapterElement = childKernel.Get<IUiElement>("AutomationElement.NET", singleElement); // // if (Preferences.UseElementsPatternObjectModel) { // // IUiElement proxiedTypedUiElement = // ConvertToProxiedElement( // adapterElement); // // proxiedTypedUiElement.SetSourceElement<AutomationElement>(element); // // return (IUiElement)proxiedTypedUiElement; // as IUiElement; // } else { // // adapterElement.SetSourceElement<AutomationElement>(element); // // return adapterElement; // } // // } // catch (Exception eFailedToIssueElement) { // // TODO // // write error to error object!!! // // Console.WriteLine("Element 01 via ChildKernel"); // // Console.WriteLine(eFailedToIssueElement.Message); // return null; // } // } public static IUiElement GetUiElement(classic.AutomationElement element) { if (null == element) { return(null); } try { var singleElement = new ConstructorArgument("element", element); // 20140122 IUiElement adapterElement; // = Kernel.Get<IUiElement>("AutomationElement.NET", singleElement); // if (null != ChildKernel) { //Console.WriteLine("child elt"); // adapterElement = ChildKernel.Get<IUiElement>("AutomationElement.NET", singleElement); // var childKernel = GetChildKernel(); // adapterElement = childKernel.Get<IUiElement>("AutomationElement.NET", singleElement); adapterElement = ChildKernel.Get <IUiElement>("AutomationElement.NET", singleElement); // childKernel.Dispose(); // (adapterElement as UiElement).ChildKernel = childKernel; // } else { // adapterElement = Kernel.Get<IUiElement>("AutomationElement.NET", singleElement); // } // 20140313 // if (Preferences.UseElementsPatternObjectModel) { // if (Preferences.UseElementsPatternObjectModel || Preferences.UseElementsSearchObjectModel || Preferences.UseElementsCached || Preferences.UseElementsCurrent) { // if (Preferences.UseElementsPatternObjectModel || Preferences.UseElementsCached || Preferences.UseElementsCurrent) { if (Preferences.UseProxy) { IUiElement proxiedTypedUiElement = ConvertToProxiedElement( adapterElement); proxiedTypedUiElement.SetSourceElement <classic.AutomationElement>(element); return((IUiElement)proxiedTypedUiElement); // as IUiElement; } else { adapterElement.SetSourceElement <classic.AutomationElement>(element); return(adapterElement); } } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Element 01"); // Console.WriteLine(eFailedToIssueElement.Message); return(null); } }
// internal static #endregion Common objects #region IUiElement // 20140210 internal static IExtendedModelHolder GetUiExtendedModelHolder(IUiElement parentElement, classic.TreeScope scope) // internal static IExtendedModelHolder GetUiExtendedModelHolder(IUiElement parentElement, TreeScope scope, int seconds) { if (null == parentElement) { return(null); } try { // 20140122 // IExtendedModelHolder holder = Kernel.Get<IExtendedModelHolder>(new IParameter[] {}); IExtendedModelHolder holder; // if (null != ChildKernel) { // holder = ChildKernel.Get<IExtendedModelHolder>(new IParameter[] {}); // var childKernel = GetChildKernel(); // if (null == (parentElement as UiElement).ChildKernel) { // (parentElement as UiElement).ChildKernel = GetChildKernel(); // } // holder = childKernel.Get<IExtendedModelHolder>(new IParameter[] {}); // holder = (parentElement as UiElement).ChildKernel.Get<IExtendedModelHolder>(new IParameter[] {}); // childKernel.Dispose(); // 20140210 holder = ChildKernel.Get <IExtendedModelHolder>(new IParameter[] {}); // var paramSeconds = new ConstructorArgument("seconds", seconds); // holder = ChildKernel.Get<IExtendedModelHolder>(paramSeconds); // (parentElement as UiElement).ChildKernel.Dispose(); // } else { // holder = Kernel.Get<IExtendedModelHolder>(new IParameter[] {}); // } var proxiedHolder = (IExtendedModelHolder)_generator.CreateClassProxy( typeof(UiExtendedModelHolder), new Type[] { typeof(IExtendedModel) }, new MethodSelectorAspect()); proxiedHolder.SetScope(scope); proxiedHolder.SetParentElement(parentElement); return(proxiedHolder); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Holder"); // Console.WriteLine(eFailedToIssueHolder.Message); return(null); } }
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>()); }
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>(); }
public void NinjectLogicWithChild() { var i = 0; while (true) { var kernel = new StandardKernel(); kernel.Bind <SampleOne>().ToSelf().InTransientScope(); kernel.Bind <SampleTwo>().ToSelf().InTransientScope(); kernel.Bind <SampleThree>().ToSelf().InTransientScope(); var child = new ChildKernel(kernel); var one = child.Get <SampleOne>(); var two = child.Get <SampleTwo>(); var three = child.Get <SampleThree>(); i++; if (i > loopCnt) { break; } } }
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); }
public void NinjectX10LogicWithChild() { var i = 0; while (true) { var kernel = new StandardKernel(); kernel.Bind <SampleOne>().ToSelf().InTransientScope(); kernel.Bind <SampleTwo>().ToSelf().InTransientScope(); kernel.Bind <SampleThree>().ToSelf().InTransientScope(); kernel.Bind <SampleFour>().ToSelf().InTransientScope(); kernel.Bind <SampleFive>().ToSelf().InTransientScope(); kernel.Bind <SampleSix>().ToSelf().InTransientScope(); kernel.Bind <SampleSeven>().ToSelf().InTransientScope(); kernel.Bind <SampleEight>().ToSelf().InTransientScope(); kernel.Bind <SampleNine>().ToSelf().InTransientScope(); kernel.Bind <SampleTen>().ToSelf().InTransientScope(); var child = new ChildKernel(kernel); var one = child.Get <SampleOne>(); var two = child.Get <SampleTwo>(); var three = child.Get <SampleThree>(); var four = child.Get <SampleThree>(); var five = child.Get <SampleThree>(); var six = child.Get <SampleThree>(); var seven = child.Get <SampleThree>(); var eight = child.Get <SampleThree>(); var nine = child.Get <SampleThree>(); var ten = child.Get <SampleThree>(); i++; if (i > loopCnt) { break; } } }
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); }
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); }
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>()); }
internal static IUiEltCollection GetUiEltCollection() { try { var boolArgument = new ConstructorArgument("fake", true); // IUiEltCollection adapterCollection = Kernel.Get<IUiEltCollection>("Empty", boolArgument); IUiEltCollection adapterCollection = ChildKernel.Get <IUiEltCollection>("Empty", boolArgument); return(adapterCollection); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Collection 04"); // Console.WriteLine(eFailedToIssueCollection.Message); return(null); } }
public void ChildKernel_IFooBoundInParentAndChildKernel_ChildCanResolveIFoo() { // Assemble var parentKernel = new StandardKernel(); parentKernel.Bind <IFoo>().To <Foo1>(); var childKernel = new ChildKernel(parentKernel); childKernel.Bind <IFoo>().To <Foo2>(); // Act var foo = childKernel.Get <IFoo>(); // Act Assert.IsInstanceOf <Foo2>(foo); }
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")); }
internal static N GetPatternAdapter <N>(object pattern) where N : IBasePattern { try { N adapterPattern = default(N); // adapterPattern = Kernel.Get<N>(NamedParameter_WithoutElement, null); adapterPattern = ChildKernel.Get <N>(NamedParameter_WithoutElement, null); adapterPattern.SetSourcePattern(pattern); return(adapterPattern); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Pattern"); // Console.WriteLine(eFailedToIssuePattern.Message); // return null; return(default(N)); } }
internal static N GetPatternAdapter <N>(IUiElement element, object pattern) where N : IBasePattern { try { N adapterPattern = default(N); var argElement = new ConstructorArgument("element", element); // adapterPattern = Kernel.Get<N>(NamedParameter_WithoutPattern, new[] { argElement }); adapterPattern = ChildKernel.Get <N>(NamedParameter_WithoutPattern, new[] { argElement }); adapterPattern.SetSourcePattern(pattern); return(adapterPattern); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Pattern"); // Console.WriteLine(eFailedToIssuePattern.Message); // return null; return(default(N)); } }
internal static IUiEltCollection GetUiEltCollection(IEnumerable elements) { if (null == elements) { return(null); } try { var manyElements = new ConstructorArgument("elements", elements); // IUiEltCollection adapterCollection = Kernel.Get<IUiEltCollection>("AnyCollection", manyElements); IUiEltCollection adapterCollection = ChildKernel.Get <IUiEltCollection>("AnyCollection", manyElements); return(adapterCollection); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Collection 03"); // Console.WriteLine(eFailedToIssueCollection.Message); return(null); } }
internal static IInputSimulator GetInputSimulator() { try { // 20140122 // return Kernel.Get<InputSimulator>(new IParameter[] {}); // if (null != ChildKernel) { // return ChildKernel.Get<InputSimulator>(new IParameter[] {}); // var childKernel = GetChildKernel(); // return childKernel.Get<InputSimulator>(new IParameter[] {}); // childKernel.Dispose(); return(ChildKernel.Get <InputSimulator>(new IParameter[] {})); // } else { // return Kernel.Get<InputSimulator>(new IParameter[] {}); // } } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("InputSimulator"); // Console.WriteLine(eFailedToIssueInputSimulator.Message); return(null); } }
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>()); }
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); }
// to prevent from threading lock internal static IUiElement GetUiElement() { try { // 20140122 IUiElement adapterElement; // = Kernel.Get<IUiElement>("Empty", null); // var childKernel = GetChildKernel(); // adapterElement = childKernel.Get<IUiElement>("Empty", null); adapterElement = ChildKernel.Get <IUiElement>("Empty", null); // childKernel.Dispose(); // (adapterElement as UiElement).ChildKernel = childKernel; // 20140313 // if (Preferences.UseElementsPatternObjectModel) { // if (Preferences.UseElementsPatternObjectModel || Preferences.UseElementsSearchObjectModel || Preferences.UseElementsCached || Preferences.UseElementsCurrent) { // if (Preferences.UseElementsPatternObjectModel || Preferences.UseElementsCached || Preferences.UseElementsCurrent) { if (Preferences.UseProxy) { IUiElement proxiedTypedUiElement = ConvertToProxiedElement( adapterElement); return((IUiElement)proxiedTypedUiElement); } else { return(adapterElement); } } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Element 03"); // Console.WriteLine(eFailedToIssueElement.Message); return(null); } }
internal static T GetHolder <T>(IUiElement parentElement) { if (null == parentElement) { return(default(T)); } try { // 20140122 // T holder = Kernel.Get<T>(new IParameter[] {}); T holder; // if (null != ChildKernel) { // holder = ChildKernel.Get<T>(new IParameter[] {}); // var childKernel = GetChildKernel(); // if (null == (parentElement as UiElement).ChildKernel) { // (parentElement as UiElement).ChildKernel = GetChildKernel(); // } // holder = childKernel.Get<T>(new IParameter[] {}); // holder = (parentElement as UiElement).ChildKernel.Get<T>(new IParameter[] {}); holder = ChildKernel.Get <T>(new IParameter[] {}); // childKernel.Dispose(); // (parentElement as UiElement).ChildKernel.Dispose(); // ChildKernel.Dispose(); // } else { // holder = Kernel.Get<T>(new IParameter[] {}); // } Type typeOfClass = null; Type wearedInterface = null; switch (typeof(T).Name) { case "IControlInputHolder": typeOfClass = typeof(UiControlInputHolder); wearedInterface = typeof(IControlInput); break; case "IKeyboardInputHolder": typeOfClass = typeof(UiKeyboardInputHolder); wearedInterface = typeof(IKeyboardInput); break; case "IMouseInputHolder": typeOfClass = typeof(UiMouseInputHolder); wearedInterface = typeof(IMouseInput); break; case "ITouchInputHolder": typeOfClass = typeof(UiTouchInputHolder); wearedInterface = typeof(ITouchInput); break; } var proxiedHolder = (T)_generator.CreateClassProxy( typeOfClass, new Type[] { wearedInterface }, new MethodSelectorAspect()); (proxiedHolder as IHolder).SetParentElement(parentElement); return(proxiedHolder); } catch (Exception) { // TODO // write error to error object!!! // Console.WriteLine("Holder"); // Console.WriteLine(eFailedToIssueHolder.Message); return(default(T)); } }
internal async Task <bool> Start(HostControl hostControl) { _hostControl = hostControl; _log.Info("Starting Hosted Microservice..."); int retries = MaxRetries; while (retries > 0) { var childKernel = new ChildKernel(_kernel); var configuration = childKernel.Get <HostedServiceConfiguration>(); var startup = childKernel.Get <Startup>(); var deferredRegistration = await _discovery.RegisterServiceDeferred(); if (configuration.RestApiPort > 0) { var apiUri = $"http://{configuration.RestApiHostname}:{configuration.RestApiPort}"; try { _app = WebApp.Start(apiUri, startup.Configuration); _log.Info($"Started API at {apiUri}"); _registration = await _discovery.RegisterService(deferredRegistration); MonitorServiceRegistration(_cancellationTokenSource.Token); _inServiceWorkers = childKernel.GetAll <IInServiceWorker>().ToArray(); if (_inServiceWorkers.Any()) { _inServiceWorkers.ToList().ForEach(worker => worker.Start(_cancellationTokenSource.Token)); _log.Info($"Startd {_inServiceWorkers.Count()} in service workers"); } return(true); } catch (Exception ex) { _log.Warn($"Failed to start the API host on {apiUri}: {ex.Message}"); while (ex.InnerException != null) { _log.Debug(ex.Message); ex = ex.InnerException; } if (_app != null) { _app.Dispose(); _app = null; } _log.Info($"Retrying...({MaxRetries - retries}/{MaxRetries})"); configuration.RestApiPort = 0; retries--; } } else { retries = 0; } await Task.Delay(RetryPeriodInSeconds * 1000, _cancellationTokenSource.Token); } _discovery.DeregisterService(_registration); _log.Fatal($"Could not start API due to one or more fatal errors"); return(false); }
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); }