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


C# Container.RegisterCollection方法代码示例

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


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

示例1: Intercept_CollectionWithRegistrationInstances_InterceptsTheInstances

        public void Intercept_CollectionWithRegistrationInstances_InterceptsTheInstances()
        {
            var logger = new FakeLogger();

            var container = new Container();

            container.RegisterSingleton<ILogger>(logger);
            container.RegisterCollection<ICommand>(new[] 
            {
                Lifestyle.Transient.CreateRegistration(typeof(ICommand), typeof(ConcreteCommand), container),
                Lifestyle.Transient.CreateRegistration(typeof(ConcreteCommand), container),
            });

            container.InterceptWith<InterceptorThatLogsBeforeAndAfter>(IsACommandPredicate);

            container.RegisterInitializer<InterceptorThatLogsBeforeAndAfter>(i => i.BeforeText = "Log ");

            // Act
            var commands = container.GetAllInstances<ICommand>().ToList();

            commands.ForEach(Execute);

            // Assert
            Assert.AreEqual("Log Log ", logger.Message);
        }
开发者ID:abatishchev,项目名称:SimpleInjector,代码行数:25,代码来源:InterceptorExtensionsTests.cs

示例2: 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

示例3: BuildMediator

        private static IMediator BuildMediator()
        {
            var container = new Container();
            var assemblies = GetAssemblies().ToArray();
            container.RegisterSingleton<IMediator, Mediator>();
            container.Register(typeof(IRequestHandler<,>), assemblies);
            container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
            container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
            container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
            container.RegisterSingleton(Console.Out);
            container.RegisterSingleton(new SingleInstanceFactory(container.GetInstance));
            container.RegisterSingleton(new MultiInstanceFactory(container.GetAllInstances));

            container.Verify();

            var mediator = container.GetInstance<IMediator>();

            return mediator;
        }
开发者ID:khaledm,项目名称:MediatR,代码行数:19,代码来源:Program.cs

示例4: Analyze_ConfigurationWithCollectionRegistration_DoesNotProduceAnyWarnings

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

            container.RegisterCollection<IPlugin>(new[] { typeof(SomePluginImpl) });

            container.Verify();

            // Act
            var results = Analyzer.Analyze(container);

            // Assert
            Assert.AreEqual(0, results.Length,
                "Since the SomePluginImpl is registered explicitly using the RegisterAll method, this " +
                "registration should contain no warnings, but the following warnings are present: \"" +
                string.Join(" ", results.Select(result => result.Description)) + "\"");
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:18,代码来源:ExternalProducerCreationAnalysisTests.cs

示例5: Analyze_ComponentDependingOnReadOnlyCollectionForRegisteredCollection_DoesNotReturnsAWarning

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

            container.Register<Consumer<IReadOnlyCollection<ILogger>>>();

            // Since this collection is registered, the previous registration should not yield a warning.
            container.RegisterCollection<ILogger>(new[] { typeof(NullLogger) });

            container.Verify();

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

            // Assert
            Assert.AreEqual(0, results.Length, "actual: " + string.Join(" - ", results.Select(r => r.Description)));
        }
开发者ID:MichaelSagalovich,项目名称:SimpleInjector,代码行数:19,代码来源:ContainerRegisteredServiceContainerAnalyzerTests.full.cs

示例6: Container

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

            container.Register(typeof(IGeneric<>), typeof(GenericType<>));

            container.RegisterCollection<IPlugin>(new[] { typeof(PluginWith8Dependencies) });

            container.Verify();
            
            // Act
            var results = Analyzer.Analyze(container);

            // Assert
            Assert.AreEqual(1, results.Length, "An SRP violation is expected.");

            Assert.AreEqual(1, results.OfType<SingleResponsibilityViolationDiagnosticResult>().Count(),
                "An SRP violation is expected.");
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:20,代码来源:ExternalProducerCreationAnalysisTests.cs

示例7: 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

示例8: Analyze_TwoDelegateRegistrationsForTheSameConcreteServiceType_DoesNotReturnAWarning

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

            var reg1 = Lifestyle.Singleton.CreateRegistration<FooBar>(() => new FooBar(), container);
            var reg2 = Lifestyle.Singleton.CreateRegistration<FooBar>(() => new FooBarSub(), container);

            container.RegisterCollection(typeof(IFoo), new[] { reg1, reg2 });

            container.Verify();

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

            // Assert
            Assert.AreEqual(0, results.Length,
                "Since the two registrations both use a delegate, there's no way of knowing what the actual " +
                "implementation type is, and we should therefore not see a warning in this case. " +
                Actual(results));
        }
开发者ID:BrettJaner,项目名称:SimpleInjector,代码行数:21,代码来源:TornLifestyleContainerAnalyzerTests.cs

示例9: Container

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

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

            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(TransactionHandlerDecorator<>));
            container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ContextualHandlerDecorator<>));

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

            DecoratorContext context = decorator.Context;

            // Assert
            Assert.AreSame(typeof(ICommandHandler<RealCommand>), context.ServiceType);
            Assert.AreSame(typeof(RealCommandHandler), context.ImplementationType);
            Assert.AreSame(typeof(TransactionHandlerDecorator<RealCommand>), context.AppliedDecorators.Single());
            Assert.AreEqual("new TransactionHandlerDecorator`1(new RealCommandHandler())",
                context.Expression.ToString());
            Assert.AreEqual("ServiceType = ICommandHandler<RealCommand>, ImplementationType = RealCommandHandler",
                context.DebuggerDisplay);
        }
开发者ID:virasak,项目名称:SimpleInjector,代码行数:25,代码来源:DecoratorCollectionTests.cs

示例10: GetAllInstances_UncontrolledRegisterDecoratorWithPredicateReturningFalse_DoesNotCallTheFactory

        public void GetAllInstances_UncontrolledRegisterDecoratorWithPredicateReturningFalse_DoesNotCallTheFactory()
        {
            // Arrange
            bool decoratorTypeFactoryCalled = false;

            var container = new Container();

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

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

            var parameters = RegisterDecoratorFactoryParameters.CreateValid();

            parameters.Predicate = context => false;
            parameters.ServiceType = typeof(ICommandHandler<>);

            parameters.DecoratorTypeFactory = context =>
            {
                decoratorTypeFactoryCalled = true;
                return typeof(TransactionHandlerDecorator<>);
            };

            container.RegisterDecorator(parameters);

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

            // Assert
            Assert.IsFalse(decoratorTypeFactoryCalled, @"
                The factory should not be called if the predicate returns false. This prevents the user from 
                having to do specific handling when the decorator type can't be constructed because of generic 
                type constraints.");
        }
开发者ID:virasak,项目名称:SimpleInjector,代码行数:33,代码来源:DecoratorCollectionTests.cs

示例11: RegisterAll_RegisteringAnInternalType_ThrowsExpectedException

        public void RegisterAll_RegisteringAnInternalType_ThrowsExpectedException()
        {
            // Arrange
            string expectedMessage = ExpectedSandboxFailureExpectedMessage;

            var container = new Container();

            IEnumerable instances = new[] { new InternalServiceImpl(null) };

            try
            {
                // Act
                container.RegisterCollection(typeof(IInternalService), instances);

                Assert.Fail("The call is expected to fail inside a Silverlight sandbox.");
            }
            catch (ArgumentException ex)
            {
                // Assert
                AssertThat.StringContains(expectedMessage, ex.Message);
            }
        }
开发者ID:jamesqo,项目名称:SimpleInjector,代码行数:22,代码来源:SilverlightSpecificTests.cs

示例12: VisualizeObjectGraph_DelayedCyclicReference_VisualizesTheExpectedObjectGraph

        public void VisualizeObjectGraph_DelayedCyclicReference_VisualizesTheExpectedObjectGraph()
        {
            // Arrange
            string expectedGraph = @"InstanceProducerTests.NodeFactory(
    IEnumerable<InstanceProducerTests.INode>(
        InstanceProducerTests.NodeFactory(
            IEnumerable<InstanceProducerTests.INode>(/* cyclic dependency graph detected */))))";

            var container = new Container();

            // class NodeOne(INodeFactory factory)
            container.RegisterCollection<INode>(new[] { typeof(NodeOne) });

            // class NodeFactory(IEnumerable<INode>)
            container.Register<INodeFactory, NodeFactory>();

            container.Verify();

            var registration = container.GetRegistration(typeof(INodeFactory));

            // Act
            // Since the dependency is delayed,
            string actualGraph = registration.VisualizeObjectGraph();

            // Assert
            Assert.AreEqual(expectedGraph, actualGraph);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:27,代码来源:InstanceProducerTests.cs

示例13: Analyze_TwoSingletonRegistrationsForTheSameConcreteType_ReturnsTheExpectedWarning

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

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

            container.RegisterCollection(typeof(IFoo), new[] { reg1, reg2 });

            container.Verify(VerificationOption.VerifyOnly);

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

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

示例14: 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


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