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


C# Container.RegisterDecorator方法代码示例

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


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

示例1: GCCollect_OnUnreferencedVerifiedContainersWithDecorators_CollectsThoseContainers

        public void GCCollect_OnUnreferencedVerifiedContainersWithDecorators_CollectsThoseContainers()
        {
            // Arrange
            Func<Container> buildContainer = () =>
            {
                var container = new Container();
                container.Options.EnableDynamicAssemblyCompilation = false;
                container.Register<INonGenericService, RealNonGenericService>();

                container.RegisterDecorator<INonGenericService, NonGenericServiceDecorator>();

                container.GetInstance<INonGenericService>();

                container.Dispose();

                return container;
            };

            var containers =
                Enumerable.Range(0, 10).Select(_ => new WeakReference(buildContainer())).ToArray();

            // Act
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            // Assert
            Assert.AreEqual(0, containers.Count(c => c.IsAlive), "We've got a memory leak.");
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:29,代码来源:ConsistencyTests.cs

示例2: GetInstance_OnRegisterRuntimeDecoratorRegistrationAndSingletonProxy_DecorationCanBeChangedDynamically

        public void GetInstance_OnRegisterRuntimeDecoratorRegistrationAndSingletonProxy_DecorationCanBeChangedDynamically()
        {
            // Arrange
            var container = new Container();

            bool decorateHandler = false;

            container.Register<ICommandHandler<RealCommand>, NullCommandHandler<RealCommand>>();

            container.RegisterRuntimeDecorator(typeof(ICommandHandler<>), typeof(CommandHandlerDecorator<>),
                c => decorateHandler);

            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(CommandHandlerProxy<>), Lifestyle.Singleton);

            // Act
            var handler1 = 
                ((CommandHandlerProxy<RealCommand>)container.GetInstance<ICommandHandler<RealCommand>>())
                .DecorateeFactory();

            // Runtime switch
            decorateHandler = true;

            var handler2 = 
                ((CommandHandlerProxy<RealCommand>)container.GetInstance<ICommandHandler<RealCommand>>())
                .DecorateeFactory();

            // Assert
            AssertThat.IsInstanceOfType(typeof(NullCommandHandler<RealCommand>), handler1);
            AssertThat.IsInstanceOfType(typeof(CommandHandlerDecorator<RealCommand>), handler2);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:30,代码来源:RuntimeDecoratorExtensionsTests.cs

示例3: Scenario1

        public void Scenario1()
        {
            // Arrange
            var container = new Container();

            var plugins = new KeyedRegistrations<string, IPlugin>(container);

            container.Options.DependencyInjectionBehavior = new NamedDependencyInjectionBehavior(
                container.Options.DependencyInjectionBehavior,
                (serviceType, name) => plugins.GetRegistration(name));

            plugins.Register(typeof(Plugin1), "1");
            plugins.Register<Plugin2>("2");
            plugins.Register(typeof(Plugin3), "3", Lifestyle.Singleton);
            plugins.Register(() => new Plugin("4"), "4");
            plugins.Register(() => new Plugin("5"), "5", Lifestyle.Singleton);

            container.RegisterCollection<IPlugin>(plugins);

            container.RegisterDecorator(typeof(IPlugin), typeof(PluginDecorator), Lifestyle.Singleton,
                context => context.ImplementationType == typeof(Plugin3));

            container.RegisterSingleton<Func<string, IPlugin>>(key => plugins.GetInstance(key));

            container.Verify();

            // Act
            var actualPlugins1 = container.GetAllInstances<IPlugin>().ToArray();
            var actualPlugins2 = container.GetAllInstances<IPlugin>().ToArray();
            var factory = container.GetInstance<Func<string, IPlugin>>();
            var consumer = container.GetInstance<NamedPluginConsumer>();

            // Assert
            AssertThat.IsInstanceOfType(typeof(Plugin1), actualPlugins1[0]);
            AssertThat.IsInstanceOfType(typeof(Plugin2), actualPlugins1[1]);
            AssertThat.IsInstanceOfType(typeof(PluginDecorator), actualPlugins1[2]);
            AssertThat.IsInstanceOfType(typeof(Plugin), actualPlugins1[3]);
            AssertThat.IsInstanceOfType(typeof(Plugin), actualPlugins1[4]);

            AssertThat.IsInstanceOfType(typeof(Plugin1), factory("1"));
            AssertThat.IsInstanceOfType(typeof(Plugin2), factory("2"));
            AssertThat.IsInstanceOfType(typeof(PluginDecorator), factory("3"));
            AssertThat.IsInstanceOfType(typeof(Plugin), factory("4"));
            AssertThat.IsInstanceOfType(typeof(Plugin), factory("5"));

            Assert.AreNotSame(actualPlugins1[0], actualPlugins2[0]);
            Assert.AreNotSame(actualPlugins1[1], actualPlugins2[1]);
            Assert.AreSame(actualPlugins1[2], actualPlugins2[2]);
            Assert.AreNotSame(actualPlugins1[3], actualPlugins2[3]);
            Assert.AreSame(actualPlugins1[4], actualPlugins2[4]);

            AssertThat.IsInstanceOfType(typeof(Plugin1), consumer.Plugin1);
            AssertThat.IsInstanceOfType(typeof(Plugin2), consumer.Plugin2);
            AssertThat.IsInstanceOfType(typeof(PluginDecorator), consumer.Plugin3);
            AssertThat.IsInstanceOfType(typeof(Plugin), consumer.Plugin4);
        }
开发者ID:BrettJaner,项目名称:SimpleInjector,代码行数:56,代码来源:KeyedRegistrationsTests.cs

示例4: Analyze_ContainerWithOneMismatchCausedByDecorator_ReturnsExpectedWarning

        public void Analyze_ContainerWithOneMismatchCausedByDecorator_ReturnsExpectedWarning()
        {
            // Arrange
            var container = new Container();
            container.Options.SuppressLifestyleMismatchVerification = true;

            container.Register<ILogger, ConsoleLogger>(Lifestyle.Singleton);
            container.RegisterDecorator<ILogger, LoggerDecorator>(Lifestyle.Transient);

            // RealUserService depends on IUserRepository
            container.Register<ServiceWithDependency<ILogger>>(Lifestyle.Singleton);

            container.Verify(VerificationOption.VerifyOnly);

            // Act
            var result = Analyzer.Analyze(container).OfType<PotentialLifestyleMismatchDiagnosticResult>().Single();

            // Assert
            Assert.AreEqual(
                "ServiceWithDependency<ILogger> (Singleton) depends on ILogger implemented by " +
                "LoggerDecorator (Transient).",
                result.Description);
        }
开发者ID:MichaelSagalovich,项目名称:SimpleInjector,代码行数:23,代码来源:PotentialLifestyleMismatchContainerAnalyzerTests.cs

示例5: GetInstance_SingletonRegistrationWithTransientDecorator_WrapsThatSingleInstance

        public void GetInstance_SingletonRegistrationWithTransientDecorator_WrapsThatSingleInstance()
        {
            // Arrange
            var container = new Container();

            container.Register<IService1, IService2, ImplementsBothInterfaces>(Lifestyle.Singleton);

            container.RegisterDecorator(typeof(IService2), typeof(Service2Decorator));

            // Act
            var service1 = container.GetInstance<IService1>();
            var decorator = (Service2Decorator)container.GetInstance<IService2>();

            // Assert
            Assert.IsNotNull(decorator.DecoratedService);
            Assert.IsTrue(object.ReferenceEquals(service1, decorator.DecoratedService));
        }
开发者ID:jamesqo,项目名称:SimpleInjector,代码行数:17,代码来源:MultiKeyedRegistrationsExtensionsTests.cs

示例6: Container

        public void GetAllInstances_UncontrolledRegisterDecoratorWithFactoryReturningAPartialOpenGenericType_WorksLikeACharm()
        {
            // Arrange
            var container = new Container();

            IEnumerable<ICommandHandler<RealCommand>> uncontrolledCollection = new[] { new RealCommandHandler() };

            container.RegisterCollection<ICommandHandler<RealCommand>>(uncontrolledCollection);

            var parameters = RegisterDecoratorFactoryParameters.CreateValid();

            parameters.ServiceType = typeof(ICommandHandler<>);

            // Here we make a partial open-generic type by filling in the TUnresolved.
            parameters.DecoratorTypeFactory = context =>
                typeof(CommandHandlerDecoratorWithUnresolvableArgument<,>)
                    .MakePartialOpenGenericType(
                        secondArgument: context.ImplementationType);

            container.RegisterDecorator(parameters);

            // Act
            var handler = container.GetAllInstances<ICommandHandler<RealCommand>>().Single();

            // Assert
            AssertThat.AreEqual(
                typeof(CommandHandlerDecoratorWithUnresolvableArgument<RealCommand, ICommandHandler<RealCommand>>),
                actualType: handler.GetType());
        }
开发者ID:virasak,项目名称:SimpleInjector,代码行数:29,代码来源:DecoratorCollectionTests.cs

示例7: GetInstance_OnInstanceWithDecorator_AppliesDecorator

        public void GetInstance_OnInstanceWithDecorator_AppliesDecorator()
        {
            // Arrange
            var container = new Container();

            container.Register<IService1, IService2, ImplementsBothInterfaces>(Lifestyle.Singleton);

            container.RegisterDecorator(typeof(IService2), typeof(Service2Decorator));

            // Act
            var service = container.GetInstance<IService2>();
            
            // Assert
            AssertThat.IsInstanceOfType(typeof(Service2Decorator), service);
        }
开发者ID:jamesqo,项目名称:SimpleInjector,代码行数:15,代码来源:MultiKeyedRegistrationsExtensionsTests.cs

示例8: Verify_TwoUniqueComponentsForTheSameAbstractionWithADecorator_DoesNotResultInDiagnosticWarnings

        public void Verify_TwoUniqueComponentsForTheSameAbstractionWithADecorator_DoesNotResultInDiagnosticWarnings()
        {
            // Arrange
            var container = new Container();

            var p1 = Lifestyle.Singleton.CreateProducer<ICommandHandler<RealCommand>, RealCommandHandler>(container);
            var p2 = Lifestyle.Singleton.CreateProducer<ICommandHandler<RealCommand>, NullCommandHandler<RealCommand>>(container);

            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(CommandHandlerDecorator<>), Lifestyle.Singleton);

            // Act
            container.Verify();
        }
开发者ID:BrettJaner,项目名称:SimpleInjector,代码行数:13,代码来源:TornLifestyleContainerAnalyzerTests.cs

示例9: Verify_MultipleProxyDecorators_DoesNotCauseAnyDiagnosticWarnings

        public void Verify_MultipleProxyDecorators_DoesNotCauseAnyDiagnosticWarnings()
        {
            // Arrange
            var container = new Container();

            container.Register(typeof(ICommandHandler<int>), typeof(NullCommandHandler<int>), Lifestyle.Transient);

            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AsyncCommandHandlerProxy<>), Lifestyle.Singleton);
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(AsyncCommandHandlerProxy<>), Lifestyle.Singleton);

            container.Verify(VerificationOption.VerifyOnly);

            // Act
            var results = Analyzer.Analyze(container).OfType<TornLifestyleDiagnosticResult>();

            // Assert
            Assert.IsFalse(results.Any(), Actual(results));
        }
开发者ID:BrettJaner,项目名称:SimpleInjector,代码行数:18,代码来源:TornLifestyleContainerAnalyzerTests.cs

示例10: Container

        public void GetInstance_CalledTwiceInOneScopeForDecoratedWebRequestInstance2_WrapsATransientDecoratorAroundAWebRequestInstance()
        {
            // Arrange
            var container = new Container();

            // Same as previous test, but now with RegisterDecorator called first.
            container.RegisterDecorator(typeof(ICommand), typeof(CommandDecorator));

            container.RegisterPerWebRequest<ICommand, ConcreteCommand>();

            using (new HttpContextScope())
            {
                // Act
                var decorator1 = (CommandDecorator)container.GetInstance<ICommand>();
                var decorator2 = (CommandDecorator)container.GetInstance<ICommand>();

                // Assert
                Assert.IsFalse(object.ReferenceEquals(decorator1, decorator2),
                    "The decorator should be transient but seems to have a scoped lifetime.");

                Assert.IsTrue(object.ReferenceEquals(decorator1.DecoratedInstance, decorator2.DecoratedInstance),
                    "The decorated instance should be scoped per lifetime. It seems to be transient.");
            }
        }
开发者ID:jamesqo,项目名称:SimpleInjector,代码行数:24,代码来源:SimpleInjectorWebExtensionsTests.cs

示例11: Container

        public void Analyze_TwoRegistrationsForTheSameImplementationMadeWithTheSameRegistrationInstanceWrappedBySingletonDecorators_DoesNotReturnsAWarning()
        {
            // Arrange
            var container = new Container();

            var reg = Lifestyle.Singleton.CreateRegistration<FooBar>(container);

            container.AddRegistration(typeof(IFoo), reg);
            container.AddRegistration(typeof(IBar), reg);

            container.RegisterDecorator(typeof(IBar), typeof(BarDecorator), Lifestyle.Singleton);

            container.Verify();

            // Act
            var results = Analyzer.Analyze(container).OfType<TornLifestyleDiagnosticResult>().ToArray();

            // Assert
            Assert.AreEqual(0, results.Length, Actual(results));
        }
开发者ID:BrettJaner,项目名称:SimpleInjector,代码行数:20,代码来源:TornLifestyleContainerAnalyzerTests.cs

示例12: GetInstance_CalledForDecoratedCollection_CallsEventForBothTheInstanceAndTheDecorator

        public void GetInstance_CalledForDecoratedCollection_CallsEventForBothTheInstanceAndTheDecorator()
        {
            // Arrange
            var actualContexts = new List<InstanceInitializationData>();

            var container = new Container();

            container.RegisterCollection<ICommandHandler<RealCommand>>(new[] { typeof(StubCommandHandler) });

            container.RegisterInitializer(actualContexts.Add, TruePredicate);

            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(RealCommandHandlerDecorator));

            // Act
            var decorator = container.GetAllInstances<ICommandHandler<RealCommand>>().Single()
                as RealCommandHandlerDecorator;

            // Assert
            // TODO: The container should actually call InstanceCreated for the IEnumerable<T> as well.
            Assert.AreEqual(2, actualContexts.Count, "Two event args were expected.");

            Assert.AreEqual(typeof(StubCommandHandler), actualContexts.First().Context.Registration.ImplementationType);
            Assert.AreEqual(typeof(RealCommandHandlerDecorator), actualContexts.Second().Context.Registration.ImplementationType);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:24,代码来源:RegisterContextualInitializerTests.cs

示例13: GetInstance_CalledForDecoratedUncontrolledCollection_CallsEventForBothTheInstanceAndTheDecorator

        public void GetInstance_CalledForDecoratedUncontrolledCollection_CallsEventForBothTheInstanceAndTheDecorator()
        {
            // Arrange
            var actualContexts = new List<InstanceInitializationData>();

            var container = new Container();

            // Container uncontrolled collection
            IEnumerable<ICommandHandler<RealCommand>> handlers = new ICommandHandler<RealCommand>[]
            {
                new StubCommandHandler(),
            };

            container.RegisterCollection<ICommandHandler<RealCommand>>(handlers);

            container.RegisterInitializer(actualContexts.Add, TruePredicate);

            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(RealCommandHandlerDecorator));

            // Act
            var producer = container.GetRegistration(typeof(IEnumerable<ICommandHandler<RealCommand>>));

            var decorator = container.GetAllInstances<ICommandHandler<RealCommand>>().Single()
                as RealCommandHandlerDecorator;

            // Assert
            Assert.AreEqual(2, actualContexts.Count, "Two event args were expected.");

            Assert.AreSame(producer, actualContexts.First().Context.Producer);
            Assert.AreSame(producer, actualContexts.Second().Context.Producer);

            Assert.AreEqual(
                typeof(IEnumerable<ICommandHandler<RealCommand>>), 
                actualContexts.First().Context.Registration.ImplementationType);

            Assert.AreEqual(
                typeof(RealCommandHandlerDecorator),
                actualContexts.Second().Context.Registration.ImplementationType);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:39,代码来源:RegisterContextualInitializerTests.cs

示例14: GetInstance_RegistrationWithDecorator_CallsInstanceCreatedForBothTheInstanceAndTheDecorator

        public void GetInstance_RegistrationWithDecorator_CallsInstanceCreatedForBothTheInstanceAndTheDecorator()
        {
            // Arrange
            var actualContexts = new List<InstanceInitializationData>();

            var container = new Container();

            container.Register<RealTimeProvider>();

            container.RegisterInitializer(actualContexts.Add, TruePredicate);

            container.Register<ICommandHandler<RealCommand>, StubCommandHandler>();
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(RealCommandHandlerDecorator));

            // Act
            var decorator = container.GetInstance<ICommandHandler<RealCommand>>() as RealCommandHandlerDecorator;

            // Assert
            Assert.AreEqual(2, actualContexts.Count, "Two event args were expected.");

            AssertThat.IsInstanceOfType(typeof(StubCommandHandler), actualContexts.First().Instance);

            AssertThat.IsInstanceOfType(typeof(RealCommandHandlerDecorator), actualContexts.Second().Instance);

            Assert.AreSame(decorator, actualContexts.Second().Instance);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:26,代码来源:RegisterContextualInitializerTests.cs

示例15: Container

        public void GetInstance_CalledTwiceForSingletonRegistrationWithTransientDecorator_CallsEventOnceForInstanceTwiceForDecorator()
        {
            // Arrange
            var actualContexts = new List<InstanceInitializationData>();

            var container = new Container();

            container.Register<RealTimeProvider>();

            container.RegisterInitializer(actualContexts.Add, TruePredicate);

            container.Register<ICommandHandler<RealCommand>, StubCommandHandler>(Lifestyle.Singleton);
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(RealCommandHandlerDecorator));

            // Act
            var decorator1 = container.GetInstance<ICommandHandler<RealCommand>>() as RealCommandHandlerDecorator;
            var decorator2 = container.GetInstance<ICommandHandler<RealCommand>>() as RealCommandHandlerDecorator;

            // Assert
            Assert.AreEqual(3, actualContexts.Count, "Three event args were expected.");

            AssertThat.IsInstanceOfType(typeof(StubCommandHandler), actualContexts.First().Instance);

            Assert.AreSame(decorator1.Decorated, actualContexts.First().Instance);

            Assert.AreEqual(
                expected: typeof(RealCommandHandlerDecorator), 
                actual: actualContexts.Second().Context.Registration.ImplementationType);

            Assert.AreSame(decorator1, actualContexts.Second().Instance);

            Assert.AreEqual(
                expected: typeof(RealCommandHandlerDecorator), 
                actual: actualContexts.Last().Context.Registration.ImplementationType);
            
            Assert.AreSame(decorator2, actualContexts.Last().Instance);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:37,代码来源:RegisterContextualInitializerTests.cs


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