当前位置: 首页>>代码示例>>C#>>正文


C# Container.GetInstance方法代码示例

本文整理汇总了C#中Container.GetInstance方法的典型用法代码示例。如果您正苦于以下问题:C# Container.GetInstance方法的具体用法?C# Container.GetInstance怎么用?C# Container.GetInstance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Container的用法示例。


在下文中一共展示了Container.GetInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Singleton_WhenFailsToConstruct_ShouldNotThrowBiDiErrorsOnFurtherAttemptsToConstruct

        public void Singleton_WhenFailsToConstruct_ShouldNotThrowBiDiErrorsOnFurtherAttemptsToConstruct()
        {
            var container = new Container(_ =>
                _.ForSingletonOf<SomeSingletonThatConnectsToDatabaseOnConstruction>()
                    .Use<SomeSingletonThatConnectsToDatabaseOnConstruction>());

            // 1st attempt : database is down, expect "Database is down" exception
            DatabaseStatus.DatabaseIsDown = true;

            Exception<StructureMapBuildException>.ShouldBeThrownBy(
                () => { container.GetInstance<SomeSingletonThatConnectsToDatabaseOnConstruction>(); })
                .InnerException.ShouldBeOfType<DivideByZeroException>()
                .Message.ShouldContain("Database is down");

            // 2nd attempt : database is still down, still expect "Database is down" exception
            Exception<StructureMapBuildException>.ShouldBeThrownBy(
                () => { container.GetInstance<SomeSingletonThatConnectsToDatabaseOnConstruction>(); })
                .InnerException.ShouldBeOfType<DivideByZeroException>()
                .Message.ShouldContain("Database is down");

            // The database has now come online.
            DatabaseStatus.DatabaseIsDown = false;

            // If the database is up, the construction of the instance should now succeed, but
            // instead still throws a bi-di error
            var attempt3 = container.GetInstance<SomeSingletonThatConnectsToDatabaseOnConstruction>();
            attempt3.ShouldNotBeNull();
        }
开发者ID:khellang,项目名称:structuremap,代码行数:28,代码来源:Bug329_bidirectional_dependencies.cs

示例2: add_batch_of_lambdas

        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");
        }
开发者ID:goraw,项目名称:structuremap,代码行数:26,代码来源:build_by_lambdas.cs

示例3: Main

        public static void Main(string[] args)
        {
            var app = new App { ShutdownMode = ShutdownMode.OnLastWindowClose };
            app.InitializeComponent();

           var container =  new Container(x=> x.AddRegistry<AppRegistry>());


           var factory = container.GetInstance<TraderWindowFactory>();
           var window = factory.Create(true);
           container.Configure(x => x.For<Dispatcher>().Add(window.Dispatcher));

            //run start up jobs
            var priceUpdater = container.GetInstance<TradePriceUpdateJob>();


            window.Show();

            app.Resources.Add(SystemParameters.ClientAreaAnimationKey, null);
            app.Resources.Add(SystemParameters.MinimizeAnimationKey, null);
            app.Resources.Add(SystemParameters.UIEffectsKey, null);


            app.Run();
        }
开发者ID:sk8tz,项目名称:TradingDemo,代码行数:25,代码来源:BootStrap.cs

示例4: can_override_lifecycle_at_instance

        public void can_override_lifecycle_at_instance()
        {
            var container = new Container(x => {
                x.For<Rule>().Singleton();

                x.For<Rule>().Add<ARule>().Named("A").Transient();
                x.For<Rule>().Add<ARule>().Named("B").AlwaysUnique();
                x.For<Rule>().Add<ARule>().Named("C");
            });

            container.Model.For<Rule>().Lifecycle.ShouldBeOfType<SingletonLifecycle>();
            container.Model.For<Rule>().Find("C").Lifecycle.ShouldBeOfType<SingletonLifecycle>();

            // 'C' is the default lifecycle for Rule (Singleton)
            container.GetInstance<Rule>("C")
                .ShouldBeTheSameAs(container.GetInstance<Rule>("C"));

            // 'A' is a transient
            container.GetInstance<Rule>("A")
                .ShouldNotBeTheSameAs(container.GetInstance<Rule>("A"));

            using (var nested = container.GetNestedContainer())
            {
                // 'B' is always unique
                nested.GetInstance<Rule>("B")
                    .ShouldNotBeTheSameAs(nested.GetInstance<Rule>("B"));
            }
        }
开发者ID:e-tobi,项目名称:structuremap,代码行数:28,代码来源:setting_lifecycle_scope.cs

示例5: choose_database

        public void choose_database()
        {
            // SAMPLE: choose_database_container_setup
            var container = new Container(_ =>
            {
                _.For<IDatabase>().Add<Database>().Named("red")
                    .Ctor<string>("connectionString").Is("*red*");

                _.For<IDatabase>().Add<Database>().Named("green")
                    .Ctor<string>("connectionString").Is("*green*");

                _.Policies.Add<InjectDatabaseByName>();
            });
            // ENDSAMPLE

            // SAMPLE: inject-database-by-name-in-usage
            // ImportantService should get the "red" database
            container.GetInstance<ImportantService>()
                .DB.As<Database>().ConnectionString.ShouldBe("*red*");

            // BigService should get the "green" database
            container.GetInstance<BigService>()
                .DB.As<Database>().ConnectionString.ShouldBe("*green*");

            // DoubleDatabaseUser gets both
            var user = container.GetInstance<DoubleDatabaseUser>();

            user.Green.As<Database>().ConnectionString.ShouldBe("*green*");
            user.Red.As<Database>().ConnectionString.ShouldBe("*red*");
            // ENDSAMPLE
        }
开发者ID:khellang,项目名称:structuremap,代码行数:31,代码来源:custom_policies.cs

示例6: nested_container_behavior_of_transients

        public void nested_container_behavior_of_transients()
        {
            // "Transient" is the default lifecycle
            // in StructureMap
            var container = new Container(_ => {
                _.For<IColor>().Use<Green>();
            });

            // In a normal Container, a "transient" lifecycle
            // Instance will be built up once in every request
            // to the Container
            container.GetInstance<IColor>()
                .ShouldNotBeTheSameAs(container.GetInstance<IColor>());

            // From a nested container, the "transient" lifecycle
            // is tracked to the nested container
            using (var nested = container.GetNestedContainer())
            {
                nested.GetInstance<IColor>()
                    .ShouldBeTheSameAs(nested.GetInstance<IColor>());

                // One more time
                nested.GetInstance<IColor>()
                    .ShouldBeTheSameAs(nested.GetInstance<IColor>());
            }
        }
开发者ID:goraw,项目名称:structuremap,代码行数:26,代码来源:nested_containers.cs

示例7: collection_types_are_all_possible_by_default

        public void collection_types_are_all_possible_by_default()
        {
            // NOTE that we do NOT make any explicit registration of 
            // IList<IWidget>, IEnumerable<IWidget>, ICollection<IWidget>, or IWidget[]
            var container = new Container(_ => {
                _.For<IWidget>().Add<AWidget>();
                _.For<IWidget>().Add<BWidget>();
                _.For<IWidget>().Add<CWidget>();
            });

            // IList<T>
            container.GetInstance<IList<IWidget>>()
                .Select(x => x.GetType())
                .ShouldHaveTheSameElementsAs(typeof(AWidget), typeof(BWidget), typeof(CWidget));

            // ICollection<T>
            container.GetInstance<ICollection<IWidget>>()
                .Select(x => x.GetType())
                .ShouldHaveTheSameElementsAs(typeof(AWidget), typeof(BWidget), typeof(CWidget));

            // Array of T
            container.GetInstance<IWidget[]>()
                .Select(x => x.GetType())
                .ShouldHaveTheSameElementsAs(typeof(AWidget), typeof(BWidget), typeof(CWidget));
        }
开发者ID:goraw,项目名称:structuremap,代码行数:25,代码来源:enumerable_instances.cs

示例8: in_get_instance_by_name

        public void in_get_instance_by_name()
        {
            var container = new Container(x =>
            {
                x.For<ILoggerHolder>().Use<BuildSessionTarget>()
                    .Named("Red");

                x.For<ILoggerHolder>().Add<LoggerHolder>()
                    .Named("Blue");

                x.For<FakeLogger>().Use(c => new FakeLogger(c.RootType));
            });

            container.GetInstance<ILoggerHolder>("Red")
                .Logger.RootType.ShouldBe(typeof (BuildSessionTarget));

            container.GetInstance<ILoggerHolder>("Blue")
                .Logger.RootType.ShouldBe(typeof (LoggerHolder));

            container.GetInstance(typeof (ILoggerHolder), "Red")
                .As<ILoggerHolder>()
                .Logger.RootType.ShouldBe(typeof (BuildSessionTarget));

            container.GetInstance(typeof (ILoggerHolder), "Blue")
                .As<ILoggerHolder>()
                .Logger.RootType.ShouldBe(typeof (LoggerHolder));
        }
开发者ID:slahn,项目名称:structuremap,代码行数:27,代码来源:BuildSession_tracks_the_parent_type_for_issue_272.cs

示例9: as_inline_dependency

        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");
        }
开发者ID:khellang,项目名称:structuremap,代码行数:35,代码来源:build_by_lambdas.cs

示例10: build_with_lambdas_1

        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");
        }
开发者ID:goraw,项目名称:structuremap,代码行数:26,代码来源:build_by_lambdas.cs

示例11: release_transient_created_by_root_container

        public void release_transient_created_by_root_container()
        {
            var container = new Container(_ => _.TransientTracking = TransientTracking.ExplicitReleaseMode);

            container.TransientTracking.ShouldBeOfType<TrackingTransientCache>();

            var transient1 = container.GetInstance<DisposableGuy>();
            var transient2 = container.GetInstance<DisposableGuy>();

            transient1.WasDisposed.ShouldBeFalse();
            transient2.WasDisposed.ShouldBeFalse();
        
            // release ONLY transient2
            container.Release(transient2);


            transient1.WasDisposed.ShouldBeFalse();
            transient2.WasDisposed.ShouldBeTrue();

            // transient2 should no longer be 
            // tracked by the container
            container.TransientTracking.Tracked
                .Single()
                .ShouldBeTheSameAs(transient1);
        }
开发者ID:slahn,项目名称:structuremap,代码行数:25,代码来源:transient_tracking_mode_specs.cs

示例12: Main

        static void Main(string[] args)
        {
            var container = new Container(cfg =>
                                          	{
                                          		cfg.AddRegistry<CalculatorRegistry>();
                                                cfg.AddRegistry<RepositoryRegistry>();

                                                cfg.For<ILogger>().Use<Logger>();
                                            });

            var productRepository = container.GetInstance<IProductRepository>();
            var product = productRepository.Find(1);

            var taxCalculator = container.GetInstance<ITaxCalculator>();
            Console.WriteLine("Tax is: {0:C}", taxCalculator.CalculateTax(product));

            container.Configure(cfg =>
                                    {
                                        cfg.For<ILogger>().Use<NullLogger>();
                                    });

            var shippingCalculator = container.GetInstance<IShippingCalculator>();
            Console.WriteLine("Shipping is: {0:C}", shippingCalculator.CalculateRate(product));

            Console.WriteLine("Are they equal? " + container.GetInstance<IShippingCalculator>().Equals(container.GetInstance<IShippingCalculator>()));
        }
开发者ID:MattHoneycutt,项目名称:Presentations,代码行数:26,代码来源:Program.cs

示例13: ejecting_all_from_a_family

        public void ejecting_all_from_a_family()
        {
            var container = new Container(x => {
                x.For<DisposedGuy>().Singleton().AddInstances(guys => {
                    guys.Type<DisposedGuy>().Named("A");
                    guys.Type<DisposedGuy>().Named("B");
                    guys.Type<DisposedGuy>().Named("C");
                });
            });

            // Fetch all the singleton objects
            var guyA = container.GetInstance<DisposedGuy>("A");
            var guyB = container.GetInstance<DisposedGuy>("B");
            var guyC = container.GetInstance<DisposedGuy>("C");

            container.Model.EjectAndRemove<DisposedGuy>();

            // All the singleton instances should be disposed
            // as they are removed from the Container
            guyA.WasDisposed.ShouldBeTrue();
            guyB.WasDisposed.ShouldBeTrue();
            guyC.WasDisposed.ShouldBeTrue();

            // And now the container no longer has any
            // registrations for DisposedGuy
            container.GetAllInstances<DisposedGuy>()
                .Any().ShouldBeFalse();
        }
开发者ID:KevM,项目名称:structuremap,代码行数:28,代码来源:ejecting_instances.cs

示例14: eject_and_remove_a_single_instance

        public void eject_and_remove_a_single_instance()
        {
            var container = new Container(x =>
            {
                x.For<DisposedGuy>().Singleton().AddInstances(guys =>
                {
                    guys.Type<DisposedGuy>().Named("A");
                    guys.Type<DisposedGuy>().Named("B");
                    guys.Type<DisposedGuy>().Named("C");
                });
            });

            // Fetch all the SingletonThing objects
            var guyA = container.GetInstance<DisposedGuy>("A");
            var guyB = container.GetInstance<DisposedGuy>("B");
            var guyC = container.GetInstance<DisposedGuy>("C");

            // Eject *only* guyA
            container.Model.For<DisposedGuy>().EjectAndRemove("A");

            // Only guyA should be disposed
            guyA.WasDisposed.ShouldBeTrue();
            guyB.WasDisposed.ShouldBeFalse();
            guyC.WasDisposed.ShouldBeFalse();

            // Now, see that guyA is really gone
            container.GetAllInstances<DisposedGuy>()
                .ShouldHaveTheSameElementsAs(guyB, guyC);
        }
开发者ID:slahn,项目名称:structuremap,代码行数:29,代码来源:ejecting_instances.cs

示例15: GetInstance_CalledOnInitializerWithPredicateReturningFalse_CallsPredicateOnceAndDelegateNever

        public void GetInstance_CalledOnInitializerWithPredicateReturningFalse_CallsPredicateOnceAndDelegateNever()
        {
            // Registration
            int expectedCallCount = 0;
            int actualCallCount = 0;
            int expectedPredicateCallCount = 1;
            int actualPredicateCallCount = 0;

            var container = new Container();

            container.RegisterInitializer(context => actualCallCount++, context =>
            {
                actualPredicateCallCount++;
                return false;
            });

            // Act
            container.GetInstance<RealTimeProvider>();
            container.GetInstance<RealTimeProvider>();
            container.GetInstance<RealTimeProvider>();
            container.GetInstance<RealTimeProvider>();
            container.GetInstance<RealTimeProvider>();

            // Assert
            Assert.AreEqual(expectedCallCount, actualCallCount);
            Assert.AreEqual(expectedPredicateCallCount, actualPredicateCallCount);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:27,代码来源:RegisterContextualInitializerTests.cs


注:本文中的Container.GetInstance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。