public FunqUseCase() { container = new Container { DefaultReuse = ReuseScope.None }; container.Register<IWebService>( c => new WebService( c.Resolve<IAuthenticator>(), c.Resolve<IStockQuote>())); container.Register<IAuthenticator>( c => new Authenticator( c.Resolve<ILogger>(), c.Resolve<IErrorHandler>(), c.Resolve<IDatabase>())); container.Register<IStockQuote>( c => new StockQuote( c.Resolve<ILogger>(), c.Resolve<IErrorHandler>(), c.Resolve<IDatabase>())); container.Register<IDatabase>( c => new Database( c.Resolve<ILogger>(), c.Resolve<IErrorHandler>())); container.Register<IErrorHandler>( c => new ErrorHandler(c.Resolve<ILogger>())); container.Register<ILogger>(new Logger()); }
public void add_batch_of_lambdas() { var container = new Container(x => { x.For<Rule>().AddInstances(rules => { // Build by a simple Expression<Func<T>> rules.ConstructedBy(() => new ColorRule("Red")).Named("Red"); // Build by a simple Expression<Func<IBuildSession, T>> rules.ConstructedBy("Blue", () => { return new ColorRule("Blue"); }).Named("Blue"); // Build by Func<T> with a user supplied description rules .ConstructedBy(s => s.GetInstance<RuleBuilder>().ForColor("Green")) .Named("Green"); // Build by Func<IBuildSession, T> with a user description rules.ConstructedBy("Purple", s => { return s.GetInstance<RuleBuilder>().ForColor("Purple"); }) .Named("Purple"); }); }); container.GetInstance<Rule>("Red").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Red"); container.GetInstance<Rule>("Blue").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Blue"); container.GetInstance<Rule>("Green").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Green"); container.GetInstance<Rule>("Purple").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Purple"); }
public void RegisterResolveArguments() { var c = new Container(); c.Register<ITest1>(() => new Test1()); var t1 = c.Resolve<ITest1>(); Assert.IsNotNull(t1); Assert.IsInstanceOfType(typeof(Test1), t1); c.Register<ITest2>(() => new Test2()); var t2 = c.Resolve<ITest2>(); Assert.IsNotNull(t2); Assert.IsInstanceOfType(typeof(Test2), t2); c.Register<ITest3, ITest1, ITest2>((a1, a2) => new Test3(a1, a2)); var t3 = c.Resolve<ITest3>(); Assert.IsNotNull(t3); Assert.IsInstanceOfType(typeof(Test3), t3); Assert.IsNotNull(t3.Test1); Assert.IsInstanceOfType(typeof(Test1), t3.Test1); Assert.IsNotNull(t3.Test2); Assert.IsInstanceOfType(typeof(Test2), t3.Test2); }
public ContentsMessage(Container container, Contents contents) { this.ContainerID = container.ID; this.Keys = contents.Keys; this.Data = contents.Data; this.Meta = contents.Meta; }
public void build_with_lambdas_1() { var container = new Container(x => { // Build by a simple Expression<Func<T>> x.For<Rule>().Add(() => new ColorRule("Red")).Named("Red"); // Build by a simple Expression<Func<IBuildSession, T>> x.For<Rule>().Add("Blue", () => { return new ColorRule("Blue"); }) .Named("Blue"); // Build by Func<T> with a user supplied description x.For<Rule>() .Add(s => s.GetInstance<RuleBuilder>().ForColor("Green")) .Named("Green"); // Build by Func<IBuildSession, T> with a user description x.For<Rule>() .Add("Purple", s => { return s.GetInstance<RuleBuilder>().ForColor("Purple"); }) .Named("Purple"); }); container.GetInstance<Rule>("Red").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Red"); container.GetInstance<Rule>("Blue").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Blue"); container.GetInstance<Rule>("Green").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Green"); container.GetInstance<Rule>("Purple").ShouldBeOfType<ColorRule>().Color.ShouldEqual("Purple"); }
public override void Reset() { base.Reset(); Clock.ProcessFrame(); Container approachContainer = new Container { Depth = float.MinValue, }; Add(approachContainer); const int count = 10; for (int i = 0; i < count; i++) { var h = new HitCircle { StartTime = Clock.CurrentTime + 1000 + i * 80, Position = new Vector2((i - count / 2) * 14), }; DrawableHitCircle d = new DrawableHitCircle(h) { Anchor = Anchor.Centre, Origin = Anchor.Centre, Depth = i, State = ArmedState.Hit, Judgement = new OsuJudgementInfo { Result = HitResult.Hit } }; approachContainer.Add(d.ApproachCircle.CreateProxy()); Add(d); } }
protected override void OnStart(string[] args) { base.OnStart(args); var container = new Container(); host = container.GetInstance<IHostService>(); host.StartServices(); }
public void FactoryTemplateTester() { var container = new Container(); container.GetInstance<Func<ConcreteClass>>()().ShouldNotBeNull(); }
public static IContainer GetContainer() { var register = new Registry(); register.IncludeRegistry<MirutradingRegistry>(); IContainer container = new Container(register); return container; }
private static IMediator BuildMediator() { var container = new Container(cfg => { cfg.Scan(scanner => { scanner.AssemblyContainingType<Ping>(); scanner.AssemblyContainingType<IMediator>(); scanner.WithDefaultConventions(); scanner.AddAllTypesOf(typeof(IRequestHandler<,>)); scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>)); scanner.AddAllTypesOf(typeof(INotificationHandler<>)); scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>)); }); cfg.For<TextWriter>().Use(Console.Out); }); var serviceLocator = new StructureMapServiceLocator(container); var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator); container.Configure(cfg => cfg.For<ServiceLocatorProvider>().Use(serviceLocatorProvider)); var mediator = serviceLocator.GetInstance<IMediator>(); return mediator; }
public void build_a_func_for_a_concrete_class() { var container = new Container(); var func = container.GetInstance<Func<ConcreteClass>>(); func().ShouldNotBeNull(); }
public void AddRange(Container.Info[] cInfo) { foreach (Container.Info cI in cInfo) { List.Add(cI); } }
private void MockServiceLocator() { var settings = new ApplicationSettings(); var configReader = new ConfigReaderWriterStub(); configReader.ApplicationSettings = settings; var registry = new RoadkillRegistry(configReader); var container = new Container(registry); container.Configure(x => { x.Scan(a => a.AssemblyContainingType<TestHelpers>()); x.For<IPageRepository>().Use(new PageRepositoryMock()); x.For<IUserContext>().Use(new UserContextStub()); }); LocatorStartup.Locator = new StructureMapServiceLocator(container, false); DependencyResolver.SetResolver(LocatorStartup.Locator); var all = container.Model.AllInstances.OrderBy(t => t.PluginType.Name) .Select(t => String.Format("{0}:{1}", t.PluginType.Name, t.ReturnedType.AssemblyQualifiedName)); Console.WriteLine(String.Join("\n", all)); }
public void RegisterClassWithoutDependencyMethod_Fail() { var c = new Container(); c.RegisterType<EmptyClass>().AsSingleton(); c.RegisterType<SampleClassWithoutClassDependencyMethod>(); SampleClassWithoutClassDependencyMethod sampleClass = null; Exception exception = null; var thread = new Thread(() => { try { sampleClass = c.Resolve<SampleClassWithoutClassDependencyMethod>(ResolveKind.FullEmitFunction); } catch (Exception ex) { exception = ex; } }); thread.Start(); thread.Join(); if (exception != null) { throw exception; } Assert.IsNotNull(sampleClass); Assert.IsNull(sampleClass.EmptyClass); }
public void as_inline_dependency() { var container = new Container(x => { // Build by a simple Expression<Func<T>> x.For<RuleHolder>() .Add<RuleHolder>() .Named("Red") .Ctor<Rule>().Is(() => new ColorRule("Red")); // Build by a simple Expression<Func<IBuildSession, T>> x.For<RuleHolder>() .Add<RuleHolder>() .Named("Blue"). Ctor<Rule>().Is("The Blue One", () => { return new ColorRule("Blue"); }); // Build by Func<T> with a user supplied description x.For<RuleHolder>() .Add<RuleHolder>() .Named("Green") .Ctor<Rule>().Is("The Green One", s => s.GetInstance<RuleBuilder>().ForColor("Green")); // Build by Func<IBuildSession, T> with a user description x.For<RuleHolder>() .Add<RuleHolder>() .Named("Purple") .Ctor<Rule>() .Is("The Purple One", s => { return s.GetInstance<RuleBuilder>().ForColor("Purple"); }); }); container.GetInstance<RuleHolder>("Red").Rule.ShouldBeOfType<ColorRule>().Color.ShouldBe("Red"); container.GetInstance<RuleHolder>("Blue").Rule.ShouldBeOfType<ColorRule>().Color.ShouldBe("Blue"); container.GetInstance<RuleHolder>("Green").Rule.ShouldBeOfType<ColorRule>().Color.ShouldBe("Green"); container.GetInstance<RuleHolder>("Purple").Rule.ShouldBeOfType<ColorRule>().Color.ShouldBe("Purple"); }
public void register_with_generic() { var container = new Container(x => { x.For<ClassThatIsBuiltByStatic>().Use(c => ClassThatIsBuiltByStatic.Build()); }); container.GetInstance<ClassThatIsBuiltByStatic>().ShouldNotBeNull(); }
public void setter_failure_description_doesnt_kill_format() { var c = new Container(ce => { ce.Policies.SetAllProperties(sc => sc.OfType<PropertyType>()); }); Exception<StructureMapBuildException>.ShouldBeThrownBy(() => { c.GetInstance<Root>(); }) .InnerException.ShouldNotBeOfType<FormatException>(); }
public void BootstrapWithStructureMap() { new StructureMapBootstraper().BootStrapTheApplication(new StructureMapApplicationRegistry()); IContainer container = new Container(); ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(container)); }
protected override void OnStart(string[] args) { try { container = new Container(x => x.AddRegistry<DependencyRegistry>()); var myDocumentStore = new DocumentStore { ConnectionStringName = "EpiFlowDB" }; var busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("EpiFlow.Messages"); busConfiguration.UseContainer<StructureMapBuilder>(c => c.ExistingContainer(container)); busConfiguration.UseSerialization<JsonSerializer>(); busConfiguration.UsePersistence<RavenDBPersistence>() .UseDocumentStoreForSubscriptions(myDocumentStore) .UseDocumentStoreForSagas(myDocumentStore) .UseDocumentStoreForTimeouts(myDocumentStore); busConfiguration.UseTransport<RabbitMQTransport>(); busConfiguration.DefineCriticalErrorAction(OnCriticalError); busConfiguration.Transactions().DisableDistributedTransactions(); if (Environment.UserInteractive && Debugger.IsAttached) { busConfiguration.EnableInstallers(); } var startableBus = Bus.Create(busConfiguration); bus = startableBus.Start(); } catch (Exception exception) { OnCriticalError("Failed to start the bus.", exception); } }
public void Setup() { _c = new Container(); c1n = new ComponentDefinition<ITestService1, TestService1>(name: "test"); c1n2 = new ComponentDefinition<ITestService1, TestService1>(name: "test2"); c2nn = new ComponentDefinition<ITestService2, TestService2>(priority: 10); c2n = new ComponentDefinition<ITestService2, TestService2>(name: "test"); }
protected void Application_Start() { // I'm not using areas... no need to register. // AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); // create a container just to pull in tenants var topContainer = new Container(); topContainer.Configure(config => { config.Scan(scanner => { // scan the tenants folder // (For some reason just passing "Tenants" doesn't seem to work, which it should according to the docs) scanner.AssembliesFromPath(Path.Combine(Server.MapPath("~/"), "Tenants")); // pull in all the tenant types scanner.AddAllTypesOf<IApplicationTenant>(); }); }); // create selectors var tenantSelector = new DefaultTenantSelector(topContainer.GetAllInstances<IApplicationTenant>()); var containerSelector = new TenantContainerResolver(tenantSelector); // clear view engines, we don't want anything other than spark ViewEngines.Engines.Clear(); // set view engine ViewEngines.Engines.Add(new TenantViewEngine(tenantSelector)); // set controller factory ControllerBuilder.Current.SetControllerFactory(new ContainerControllerFactory(containerSelector)); }
public void should_be_able_to_resolve_from_the_generic_family_expression() { var widget = new AWidget(); var container = new Container(x => x.For(typeof (IWidget)).Use(widget).Named("mine")); container.GetInstance<IWidget>("mine").ShouldBeTheSameAs(widget); }
public void use_a_func_for_a_simple_type() { var container = new Container(x => { x.For<IntHolder>().Use<IntHolder>().Ctor<int>().Is(() => 5); }); container.GetInstance<IntHolder>() .Number.ShouldBe(5); }
public void DifferentObjects_BuildUpClassWithManyClassDependencyProperties_Success() { var c = new Container(); c.RegisterType<EmptyClass>(); c.RegisterType<SampleClass>().AsSingleton(); var sampleClass1 = new SampleClassWithManyClassDependencyProperties(); var sampleClass2 = new SampleClassWithManyClassDependencyProperties(); c.BuildUp(sampleClass1, ResolveKind.PartialEmitFunction); c.BuildUp(sampleClass2, ResolveKind.PartialEmitFunction); Assert.IsNotNull(sampleClass1.EmptyClass); Assert.IsNotNull(sampleClass1.SampleClass); Assert.IsNotNull(sampleClass1.SampleClass.EmptyClass); Assert.AreNotEqual(sampleClass1.SampleClass.EmptyClass, sampleClass1.EmptyClass); Assert.IsNotNull(sampleClass2.EmptyClass); Assert.IsNotNull(sampleClass2.SampleClass); Assert.IsNotNull(sampleClass2.SampleClass.EmptyClass); Assert.AreNotEqual(sampleClass2.SampleClass.EmptyClass, sampleClass2.EmptyClass); Assert.AreNotEqual(sampleClass1, sampleClass2); Assert.AreNotEqual(sampleClass1.EmptyClass, sampleClass2.EmptyClass); Assert.AreEqual(sampleClass1.SampleClass, sampleClass2.SampleClass); Assert.AreEqual(sampleClass1.SampleClass.EmptyClass, sampleClass2.SampleClass.EmptyClass); }
public void use_a_simple_func_for_string_dependency() { var container = new Container(x => { x.For<Rule>().Use<ColorRule>().Ctor<string>().Is(() => "blue"); }); container.GetInstance<Rule>() .ShouldBeOfType<ColorRule>().Color.ShouldBe("blue"); }
public void InterceptWithGenericArgAndPredicate_TwoInterceptors_InterceptsTheInstanceWithBothInterceptors() { // Arrange var logger = new FakeLogger(); var container = new Container(); container.RegisterSingleton<ILogger>(logger); container.Register<ICommand, CommandThatLogsOnExecute>(); container.InterceptWith<InterceptorThatLogsBeforeAndAfter>(IsACommandPredicate); container.InterceptWith<InterceptorThatLogsBeforeAndAfter2>(IsACommandPredicate); container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.BeforeText = "Start1 "); container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter2>(i => i.BeforeText = "Start2 "); container.RegisterInitializer<CommandThatLogsOnExecute>(c => c.ExecuteLogMessage = "Executing"); container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.AfterText = " Done1"); container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter2>(i => i.AfterText = " Done2"); // Act var command = container.GetInstance<ICommand>(); command.Execute(); // Assert Assert.AreEqual("Start2 Start1 Executing Done1 Done2", logger.Message); }
public void Avoid_NullReferenceException_When_Getting_Undefined_Named_Instances() { using (Container myContainer = new Container()) { myContainer.GetInstance<IndividualContainers>("TEST"); } }
// Use this for initialization void Start () { rb = GetComponent<Rigidbody>(); inventory = GetComponentInChildren<Container>(); UIManager.instance.playerInventoryPanel.container = inventory; }
public void T03_Concrete_Interface() { var container = new Container(log: Write); container.RegisterSingleton<ISomeClass>(); container.RegisterSingleton<SomeClass>(); Assert.Equal(container.Resolve<SomeClass>(), container.Resolve<ISomeClass>()); }
public void get_a_nested_container_for_a_profile() { var parent = new Container(x => { x.For<IWidget>().Use<ColorWidget>() .Ctor<string>("color").Is("red"); x.Profile("green", o => { o.For<IWidget>().Use<ColorWidget>() .Ctor<string>("color").Is("green"); }); }); var child = parent.GetNestedContainer("green"); var childWidget1 = child.GetInstance<IWidget>(); var childWidget2 = child.GetInstance<IWidget>(); var childWidget3 = child.GetInstance<IWidget>(); var parentWidget = parent.GetInstance<IWidget>(); childWidget1.ShouldBeTheSameAs(childWidget2); childWidget1.ShouldBeTheSameAs(childWidget3); childWidget1.ShouldNotBeTheSameAs(parentWidget); parentWidget.ShouldBeOfType<ColorWidget>().Color.ShouldBe("red"); childWidget1.ShouldBeOfType<ColorWidget>().Color.ShouldBe("green"); }
public override void InstallBindings() { Container.Bind <ISystem>().To(x => x.AllTypes().DerivingFrom <ISystem>().InNamespaces(SystemNamespaces)).AsSingle(); Container.Bind(x => x.AllTypes().DerivingFrom <ISystem>().InNamespaces(SystemNamespaces)).AsSingle(); }
protected override void RegisterTypes() { Container.RegisterTypeForNavigation <MainPage>(); }
public Game CreateNetworkGame(Container container, BoardView boardView, NetworkServiceHost networkServiceHost, Color color) { NetworkGameCreator networkGameCreator = new NetworkGameCreator(); return(networkGameCreator.CreateGame(container, boardView, networkServiceHost, color)); }
/// <summary> /// Retourne une instance de partie dans le mode de jeu passé en paramètre /// </summary> /// <param name="mode">Mode de jeu souhaité</param> /// <returns>Une partie dans le mode de jeu passé en paramètre</returns> public Game CreateGame(Mode mode, Container container, BoardView boardView) { return(GameCreators.FindAll(x => x.Mode == mode).First().CreateGame(container, boardView)); }
// Methods public CloseSecureTrade(Container cont) : base(111) { base.EnsureCapacity(8); this.m_Stream.Write(((byte)1)); this.m_Stream.Write(Serial.op_Implicit(cont.Serial)); }
public override void InstallBindings() { Container.BindInstance(_MLReferenceImageLibrary); }
public override void Configure(Container container) { }
public SimpleInjectorInstanceProvider(Container container, Type serviceType) { this.container = container; this.serviceType = serviceType; }
public MostResolvableParametersConstructorResolutionBehavior(Container container) { this._Container = container; }
private static void InitializeContainer(Container container) { container.Register <IQuotesProvider, QuotesProvider>(Lifestyle.Scoped); }
protected override void OnTarget(Mobile from, object target) { from.RevealingAction(); Item stolen = null; object root = null; bool caught = false; if (target is Item) { root = ((Item)target).RootParent; stolen = TryStealItem((Item)target, ref caught); } else if (target is Mobile) { Container pack = ((Mobile)target).Backpack; if (pack != null && pack.Items.Count > 0) { int randomIndex = Utility.Random(pack.Items.Count); root = target; stolen = TryStealItem(pack.Items[randomIndex], ref caught); } #region Monster Stealables if (target is BaseCreature && from is PlayerMobile) { Server.Engines.CreatureStealing.StealingHandler.HandleSteal(target as BaseCreature, from as PlayerMobile); } #endregion } else { m_Thief.SendLocalizedMessage(502710); // You can't steal that! } if (stolen != null) { if (stolen is AddonComponent) { BaseAddon addon = ((AddonComponent)stolen).Addon as BaseAddon; from.AddToBackpack(addon.Deed); addon.Delete(); } else { from.AddToBackpack(stolen); } if (!(stolen is Container || stolen.Stackable)) { // do not return stolen containers or stackable items StolenItem.Add(stolen, m_Thief, root as Mobile); } } if (caught) { if (root == null) { m_Thief.CriminalAction(false); } else if (root is Corpse && ((Corpse)root).IsCriminalAction(m_Thief)) { m_Thief.CriminalAction(false); } else if (root is Mobile) { Mobile mobRoot = (Mobile)root; if (!IsInGuild(mobRoot) && IsInnocentTo(m_Thief, mobRoot)) { m_Thief.CriminalAction(false); } string message = String.Format("You notice {0} trying to steal from {1}.", m_Thief.Name, mobRoot.Name); foreach (NetState ns in m_Thief.GetClientsInRange(8)) { if (ns.Mobile != m_Thief) { ns.Mobile.SendMessage(message); } } } } else if (root is Corpse && ((Corpse)root).IsCriminalAction(m_Thief)) { m_Thief.CriminalAction(false); } if (root is Mobile && ((Mobile)root).Player && m_Thief is PlayerMobile && IsInnocentTo(m_Thief, (Mobile)root) && !IsInGuild((Mobile)root)) { PlayerMobile pm = (PlayerMobile)m_Thief; pm.PermaFlags.Add((Mobile)root); pm.Delta(MobileDelta.Noto); } }
private void InitializeComponent() { this.components = new Container(); this.lblTestResult = new Label(); this.lstStandardExpressions = new ListBox(); this.lblStandardExpressions = new Label(); this.cmdTestValidate = new Button(); this.txtExpression = new TextBox(); this.lblInput = new Label(); this.grpExpression = new GroupBox(); this.txtSampleInput = new TextBox(); this.cmdCancel = new Button(); this.lblExpression = new Label(); this.cmdOK = new Button(); Font dialogFont = UIServiceHelper.GetDialogFont(this.site); if (dialogFont != null) { this.Font = dialogFont; } if (!string.Equals(System.Design.SR.GetString("RTL"), "RTL_False", StringComparison.Ordinal)) { this.RightToLeft = RightToLeft.Yes; this.RightToLeftLayout = true; } base.MinimizeBox = false; base.MaximizeBox = false; base.ShowInTaskbar = false; base.StartPosition = FormStartPosition.CenterParent; this.Text = System.Design.SR.GetString("RegexEditor_Title"); base.ImeMode = ImeMode.Disable; base.AcceptButton = this.cmdOK; base.CancelButton = this.cmdCancel; base.Icon = null; base.FormBorderStyle = FormBorderStyle.FixedDialog; base.ClientSize = new Size(0x15c, 0xd7); base.Activated += new EventHandler(this.RegexTypeEditor_Activated); base.HelpRequested += new HelpEventHandler(this.Form_HelpRequested); base.HelpButton = true; base.HelpButtonClicked += new CancelEventHandler(this.HelpButton_Click); this.lstStandardExpressions.Location = new Point(12, 30); this.lstStandardExpressions.Size = new Size(0x144, 0x54); this.lstStandardExpressions.TabIndex = 1; this.lstStandardExpressions.SelectedIndexChanged += new EventHandler(this.lstStandardExpressions_SelectedIndexChanged); this.lstStandardExpressions.Sorted = true; this.lstStandardExpressions.IntegralHeight = true; this.lstStandardExpressions.Items.AddRange(this.CannedExpressions); this.lblStandardExpressions.Location = new Point(12, 12); this.lblStandardExpressions.Text = System.Design.SR.GetString("RegexEditor_StdExp"); this.lblStandardExpressions.Size = new Size(0x148, 0x10); this.lblStandardExpressions.TabIndex = 0; this.txtExpression.Location = new Point(12, 140); this.txtExpression.TabIndex = 3; this.txtExpression.Size = new Size(0x144, 20); this.txtExpression.TextChanged += new EventHandler(this.txtExpression_TextChanged); this.lblExpression.Location = new Point(12, 0x7a); this.lblExpression.Text = System.Design.SR.GetString("RegexEditor_ValidationExpression"); this.lblExpression.Size = new Size(0x148, 0x10); this.lblExpression.TabIndex = 2; this.cmdOK.Location = new Point(180, 180); this.cmdOK.DialogResult = DialogResult.OK; this.cmdOK.Size = new Size(0x4b, 0x17); this.cmdOK.TabIndex = 9; this.cmdOK.Text = System.Design.SR.GetString("OK"); this.cmdOK.FlatStyle = FlatStyle.System; this.cmdOK.Click += new EventHandler(this.cmdOK_Click); this.cmdCancel.Location = new Point(0x105, 180); this.cmdCancel.DialogResult = DialogResult.Cancel; this.cmdCancel.Size = new Size(0x4b, 0x17); this.cmdCancel.TabIndex = 10; this.cmdCancel.FlatStyle = FlatStyle.System; this.cmdCancel.Text = System.Design.SR.GetString("Cancel"); this.grpExpression.Location = new Point(8, 280); this.grpExpression.ImeMode = ImeMode.Disable; this.grpExpression.TabIndex = 4; this.grpExpression.TabStop = false; this.grpExpression.Text = System.Design.SR.GetString("RegexEditor_TestExpression"); this.grpExpression.Size = new Size(0x148, 80); this.grpExpression.Visible = false; this.txtSampleInput.Location = new Point(0x58, 0x18); this.txtSampleInput.TabIndex = 6; this.txtSampleInput.Size = new Size(160, 20); this.grpExpression.Controls.Add(this.lblTestResult); this.grpExpression.Controls.Add(this.txtSampleInput); this.grpExpression.Controls.Add(this.cmdTestValidate); this.grpExpression.Controls.Add(this.lblInput); this.cmdTestValidate.Location = new Point(0x100, 0x18); this.cmdTestValidate.Size = new Size(0x38, 20); this.cmdTestValidate.TabIndex = 7; this.cmdTestValidate.Text = System.Design.SR.GetString("RegexEditor_Validate"); this.cmdTestValidate.FlatStyle = FlatStyle.System; this.cmdTestValidate.Click += new EventHandler(this.cmdTestValidate_Click); this.lblInput.Location = new Point(8, 0x1c); this.lblInput.Text = System.Design.SR.GetString("RegexEditor_SampleInput"); this.lblInput.Size = new Size(80, 0x10); this.lblInput.TabIndex = 5; this.lblTestResult.Location = new Point(8, 0x38); this.lblTestResult.Size = new Size(0x138, 0x10); this.lblTestResult.TabIndex = 8; base.Controls.Add(this.txtExpression); base.Controls.Add(this.lstStandardExpressions); base.Controls.Add(this.lblStandardExpressions); base.Controls.Add(this.lblExpression); base.Controls.Add(this.grpExpression); base.Controls.Add(this.cmdCancel); base.Controls.Add(this.cmdOK); }
public override void InstallBindings() { Container.BindInterfacesAndSelfTo <AvatarMemory>().FromComponentInHierarchy().AsSingle(); Container.BindInterfacesAndSelfTo <KobeluBot>().FromComponentInHierarchy().AsSingle().NonLazy(); Container.BindInterfacesAndSelfTo <BotMessenger>().AsSingle(); }
static async Task Main(string[] args) { var pathToContentRoot = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var host = new HostBuilder() /* set cwd to the path we are executing in since * running 'dotnet run' would otherwise * set cwd to the folder it is executing from * and the json files we need are being copied to the output directory */ .UseContentRoot(pathToContentRoot) .ConfigureHostConfiguration((builder) => { builder.AddJsonFile("appsettings.json"); }) .ConfigureServices((context, services) => { // AutoMapper setup using profiles. Mapper.Initialize(cfg => { cfg.AddProfile <DeploymentProfile>(); cfg.AddProfile <TripProfile>(); cfg.AddProfile <CollisionProfile>(); cfg.AddProfile <ComplaintProfile>(); cfg.AddProfile <NeighborhoodProfile>(); cfg.AddProfile <PatternAreaProfile>(); cfg.AddProfile <StreetSegmentProfile>(); cfg.AddProfile <BicyclePathProfile>(); cfg.AddProfile <GeoJsonProfile>(); }); // use a different container with more features than the default .NET Core one var container = new Container(); container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); container.Register <ScootertownDbContext>(() => { var builder = new DbContextOptionsBuilder <ScootertownDbContext>(); builder.UseNpgsql( context.Configuration.GetConnectionString("postgres"), o => o.UseNetTopologySuite() ); var options = builder.Options; var dbContext = new ScootertownDbContext( options, new VehicleStoreOptions()); return(dbContext); }, Lifestyle.Scoped); container.Register <AreasOfInterest>(() => { var options = new AreasOfInterest { NeighborhoodsFile = Path.Combine( context.HostingEnvironment.ContentRootPath, context.Configuration.GetValue <string>("NeighborhoodsFile") ), PatternAreasFile = Path.Combine( context.HostingEnvironment.ContentRootPath, context.Configuration.GetValue <string>("PatternAreasFile") ), StreetSegmentsFile = Path.Combine( context.HostingEnvironment.ContentRootPath, context.Configuration.GetValue <string>("StreetSegmentsFile") ), BicyclePathsFile = Path.Combine( context.HostingEnvironment.ContentRootPath, context.Configuration.GetValue <string>("BicyclePathsFile") ) }; return(options); }, Lifestyle.Scoped); container.Register <APIOptions>(() => { var options = new APIOptions { BaseAddress = context.Configuration.GetValue <string>("BaseAddress") }; return(options); }, Lifestyle.Scoped); // add generic services for repositories for any geojson we'll read in container.Register <INeighborhoodRepository, NeighborhoodRepository>(Lifestyle.Scoped); container.Register <IPatternAreaRepository, PatternAreaRepository>(Lifestyle.Scoped); container.Register <IStreetSegmentRepository, StreetSegmentRepository>(Lifestyle.Scoped); container.Register <IStreetSegmentGroupRepository, StreetSegmentGroupRepository>(Lifestyle.Scoped); container.Register <IBicyclePathRepository, BicyclePathRepository>(Lifestyle.Scoped); container.Register <IBicyclePathGroupRepository, BicyclePathGroupRepository>(Lifestyle.Scoped); container.Register <ITripService, TripService>(Lifestyle.Scoped); container.Register <IDeploymentService, DeploymentService>(Lifestyle.Scoped); container.Register <ICollisionService, CollisionService>(Lifestyle.Scoped); container.Register <IComplaintService, ComplaintService>(Lifestyle.Scoped); container.Register <INeighborhoodService, NeighborhoodService>(Lifestyle.Scoped); container.Register <IPatternAreaService, PatternAreaService>(Lifestyle.Scoped); container.Register <IStreetSegmentService, StreetSegmentService>(Lifestyle.Scoped); container.Register <IBicyclePathService, BicyclePathService>(Lifestyle.Scoped); container.Register(ConfigureLogger, Lifestyle.Singleton); container.Register(typeof(ILogger <>), typeof(LoggingAdapter <>), Lifestyle.Scoped); container.Register <IMemoryCache>(() => { return(new MemoryCache(new MemoryCacheOptions())); }, Lifestyle.Singleton); container.Verify(); // use the default DI to manage our new container services.AddSingleton(container); services.AddSingleton <ILoggerFactory, LoggerFactory>(); // tell the DI container to start the application services.AddSingleton <IHostedService, Host>(); }) .ConfigureLogging((context, logging) => { logging.AddConfiguration(context.Configuration.GetSection("Logging")); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); logging.AddNLog(); NLog.LogManager.LoadConfiguration("nlog.config"); }) .ConfigureAppConfiguration((context, builder) => { }); await host.RunConsoleAsync(); }
// Associate a Container with an OptionalContentGroup via an OptionalContentMembershipDict. // This function associates a Containter with a single OptionalContentGroup and uses // a VisibilityPolicy of AnyOn. public static void AssociateOCGWithContainer(Document doc, OptionalContentGroup ocg, Container cont) { // Create an OptionalContentMembershipDict. The options here are appropriate for a // 'typical' usage; other options can be used to create an 'inverting' layer // (i.e. 'Display this content when the layer is turned OFF'), or to make the // Container's visibility depend on several OptionalContentGroups OptionalContentMembershipDict ocmd = new OptionalContentMembershipDict(doc, new OptionalContentGroup[] { ocg }, VisibilityPolicy.AnyOn); // Associate the Container with the OptionalContentMembershipDict cont.OptionalContentMembershipDict = ocmd; }
public CosmosDbService(CosmosClient dbClient, string databaseName, string containerName) { _container = dbClient.GetContainer(databaseName, containerName); }
protected override DependencyObject CreateShell() { return Container.TryResolve<Views.ConfiguratorView>(); }
public OpenContainerInteraction(SpawnCommand p_command, Int32 p_parentID, Int32 p_commandIndex) : base(p_command, p_parentID, p_commandIndex) { m_parent = Grid.FindInteractiveObject(m_parentID); m_container = Grid.FindInteractiveObject <Container>(m_targetSpawnID); DeactiveContainerIfEmpty(); }
public override void OnDeath(Container c) { base.OnDeath(c); c.Delete(); }
public CrossPairsConversionTests() { _service = Container.Resolve <IRateCalculatorService>(); }
public static void RegisterLazy <T>(this Container container) where T : class { container.Register(() => new Lazy <T>(container.GetInstance <T>)); }
public void Dispose() { DisposeNestedContainer(); Container.Dispose(); }
public override void InstallBindings() { Container.Bind <DefaultViewResolver>().ToSelf().AsSingle(); Container.Bind <RandomMovementSystem>().ToSelf().AsSingle(); }
public override void OnTalk(PlayerMobile player, bool contextMenu) { QuestSystem qs = player.Quest; if (qs is HaochisTrialsQuest) { if (HaochisTrialsQuest.HasLostHaochisKatana(player)) { qs.AddConversation(new LostSwordConversation()); return; } QuestObjective obj = qs.FindObjective(typeof(FindHaochiObjective)); if (obj != null && !obj.Completed) { obj.Complete(); return; } obj = qs.FindObjective(typeof(FirstTrialReturnObjective)); if (obj != null && !obj.Completed) { player.AddToBackpack(new LeatherDo()); obj.Complete(); return; } obj = qs.FindObjective(typeof(SecondTrialReturnObjective)); if (obj != null && !obj.Completed) { if (((SecondTrialReturnObjective)obj).Dragon) { player.AddToBackpack(new LeatherSuneate()); } obj.Complete(); return; } obj = qs.FindObjective(typeof(ThirdTrialReturnObjective)); if (obj != null && !obj.Completed) { player.AddToBackpack(new LeatherHiroSode()); obj.Complete(); return; } obj = qs.FindObjective(typeof(FourthTrialReturnObjective)); if (obj != null && !obj.Completed) { if (!((FourthTrialReturnObjective)obj).KilledCat) { Container cont = GetNewContainer(); cont.DropItem(new LeatherHiroSode()); cont.DropItem(new JinBaori()); player.AddToBackpack(cont); } obj.Complete(); return; } obj = qs.FindObjective(typeof(FifthTrialReturnObjective)); if (obj != null && !obj.Completed) { Container pack = player.Backpack; if (pack != null) { Item katana = pack.FindItemByType(typeof(HaochisKatana)); if (katana != null) { katana.Delete(); obj.Complete(); obj = qs.FindObjective(typeof(FifthTrialIntroObjective)); if (obj != null && ((FifthTrialIntroObjective)obj).StolenTreasure) { qs.AddConversation(new SixthTrialIntroConversation(true)); } else { qs.AddConversation(new SixthTrialIntroConversation(false)); } } } return; } obj = qs.FindObjective(typeof(SixthTrialReturnObjective)); if (obj != null && !obj.Completed) { obj.Complete(); return; } obj = qs.FindObjective(typeof(SeventhTrialReturnObjective)); if (obj != null && !obj.Completed) { BaseWeapon weapon = new Daisho(); BaseRunicTool.ApplyAttributesTo(weapon, Utility.Random(1, 3), 10, 30); player.AddToBackpack(weapon); BaseArmor armor = new LeatherDo(); BaseRunicTool.ApplyAttributesTo(armor, Utility.Random(1, 3), 10, 20); player.AddToBackpack(armor); obj.Complete(); return; } } }
public void RunTest1() { IFoo foo = Container.Resolve <IFoo>(); Assert.That(foo.foo(), Is.EqualTo(1)); }
/// <summary> /// Example of a code migration template from Change Feed Processor V2 to SDK V3. /// </summary> /// <returns></returns> public static async Task RunMigrationSample( string databaseId, CosmosClient client, IConfigurationRoot configuration) { await Program.InitializeAsync(databaseId, client); Console.WriteLine("Generating 10 items that will be picked up by the old Change Feed Processor library..."); await Program.GenerateItems(10, client.GetContainer(databaseId, Program.monitoredContainer)); // This is how you would initialize the processor in V2 // <ChangeFeedProcessorLibrary> ChangeFeedProcessorLibrary.DocumentCollectionInfo monitoredCollectionInfo = new ChangeFeedProcessorLibrary.DocumentCollectionInfo() { DatabaseName = databaseId, CollectionName = Program.monitoredContainer, Uri = new Uri(configuration["EndPointUrl"]), MasterKey = configuration["AuthorizationKey"] }; ChangeFeedProcessorLibrary.DocumentCollectionInfo leaseCollectionInfo = new ChangeFeedProcessorLibrary.DocumentCollectionInfo() { DatabaseName = databaseId, CollectionName = Program.leasesContainer, Uri = new Uri(configuration["EndPointUrl"]), MasterKey = configuration["AuthorizationKey"] }; ChangeFeedProcessorLibrary.ChangeFeedProcessorBuilder builder = new ChangeFeedProcessorLibrary.ChangeFeedProcessorBuilder(); var oldChangeFeedProcessor = await builder .WithHostName("consoleHost") .WithProcessorOptions(new ChangeFeedProcessorLibrary.ChangeFeedProcessorOptions { StartFromBeginning = true, LeasePrefix = "MyLeasePrefix" }) .WithProcessorOptions(new ChangeFeedProcessorLibrary.ChangeFeedProcessorOptions() { MaxItemCount = 10, FeedPollDelay = TimeSpan.FromSeconds(1) }) .WithFeedCollection(monitoredCollectionInfo) .WithLeaseCollection(leaseCollectionInfo) .WithObserver <ChangeFeedObserver>() .BuildAsync(); // </ChangeFeedProcessorLibrary> await oldChangeFeedProcessor.StartAsync(); // Wait random time for the delegate to output all messages after initialization is done await Task.Delay(5000); Console.WriteLine("Now we will stop the V2 Processor and start a V3 with the same parameters to pick up from the same state, press any key to continue..."); Console.ReadKey(); await oldChangeFeedProcessor.StopAsync(); Console.WriteLine("Generating 5 items that will be picked up by the new Change Feed Processor..."); await Program.GenerateItems(5, client.GetContainer(databaseId, Program.monitoredContainer)); // This is how you would do the same initialization in V3 // <ChangeFeedProcessorMigrated> Container leaseContainer = client.GetContainer(databaseId, Program.leasesContainer); Container monitoredContainer = client.GetContainer(databaseId, Program.monitoredContainer); ChangeFeedProcessor changeFeedProcessor = monitoredContainer .GetChangeFeedProcessorBuilder <ToDoItem>("MyLeasePrefix", Program.HandleChangesAsync) .WithInstanceName("consoleHost") .WithLeaseContainer(leaseContainer) .WithMaxItems(10) .WithPollInterval(TimeSpan.FromSeconds(1)) .WithStartTime(DateTime.MinValue.ToUniversalTime()) .Build(); // </ChangeFeedProcessorMigrated> await changeFeedProcessor.StartAsync(); // Wait random time for the delegate to output all messages after initialization is done await Task.Delay(5000); Console.WriteLine("Press any key to continue with the next demo..."); Console.ReadKey(); await changeFeedProcessor.StopAsync(); }
public static int Build( Mobile from, Point3D start, Point3D end, ConstructorInfo ctor, object[] values, string[,] props, PropertyInfo[] realProps, ArrayList packs ) { try { Map map = from.Map; int objectCount = ( packs == null ? ( ( ( end.X - start.X ) + 1 ) * ( ( end.Y - start.Y ) + 1 ) ) : packs.Count ); if ( objectCount >= 20 ) { from.SendMessage( "Constructing {0} objects, please wait.", objectCount ); } bool sendError = true; StringBuilder sb = new StringBuilder(); sb.Append( "Serials: " ); if ( packs != null ) { for ( int i = 0; i < packs.Count; ++i ) { object built = Build( from, ctor, values, props, realProps, ref sendError ); if ( built is IEntity ) { sb.AppendFormat( "0x{0:X}; ", ( (IEntity) built ).Serial.Value ); } else { continue; } if ( built is Item ) { Container pack = (Container) packs[i]; pack.DropItem( (Item) built ); } else if ( built is Mobile ) { Mobile m = (Mobile) built; m.MoveToWorld( new Point3D( start.X, start.Y, start.Z ), map ); } } } else { for ( int x = start.X; x <= end.X; ++x ) { for ( int y = start.Y; y <= end.Y; ++y ) { object built = Build( from, ctor, values, props, realProps, ref sendError ); if ( built is IEntity ) { sb.AppendFormat( "0x{0:X}; ", ( (IEntity) built ).Serial.Value ); } else { continue; } if ( built is Item ) { Item item = (Item) built; item.MoveToWorld( new Point3D( x, y, start.Z ), map ); } else if ( built is Mobile ) { Mobile m = (Mobile) built; m.MoveToWorld( new Point3D( x, y, start.Z ), map ); } } } } CommandLogging.WriteLine( from, sb.ToString() ); return objectCount; } catch ( Exception ex ) { Console.WriteLine( ex ); return 0; } }
public override Expression FromNode([Optional] Container container) { Console.WriteLine(NodeType); return(Expression.ListInit((NewExpression)NewExpression.FromNode(container), Initializers.Select(e => e.FromNode(container)))); }
public void TestInitialize() { base.TestInitialize(); ConfigurationProvider = Container.Resolve <IConfigurationProvider>(); }
public void Installer() { Container.BindInterfacesTo <Foo>().AsSingle(); }