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


C# Container.GetRegistration方法代码示例

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


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

示例1: BuildExpression_ContainerWithoutRegisterInitializerApplied_DoesNotApplyEventToExpression

        public void BuildExpression_ContainerWithoutRegisterInitializerApplied_DoesNotApplyEventToExpression()
        {
            // Registration
            var container = new Container();

            // Act
            var expression = container.GetRegistration(typeof(RealTimeProvider)).BuildExpression();

            // Assert
            Assert.AreEqual("new RealTimeProvider()", expression.ToString(),
                "The event should not be applied to the expression, since that would cause performance " +
                "penalty, much like a RegisterInitializer<object>(() => { }) would cause.");
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:13,代码来源:RegisterContextualInitializerTests.cs

示例2: InstanceProducerLifestyle_ForAScopedRegistration_HasTheExpectedDefaultScopedLifestyle

        public void InstanceProducerLifestyle_ForAScopedRegistration_HasTheExpectedDefaultScopedLifestyle()
        {
            // Arrange
            var expectedLifestyle = new LifetimeScopeLifestyle();

            var container = new Container();
            container.Options.DefaultScopedLifestyle = expectedLifestyle;

            container.Register<RealTimeProvider>(Lifestyle.Scoped);

            InstanceProducer producer = container.GetRegistration(typeof(RealTimeProvider));

            // Act
            Lifestyle actualLifestyle = producer.Lifestyle;

            // Assert
            Assert.AreSame(expectedLifestyle, actualLifestyle);
        }
开发者ID:MichaelSagalovich,项目名称:SimpleInjector,代码行数:18,代码来源:LifestyleScopedTests.cs

示例3: Analyze_TransientRegistrationForDisposableComponentWithSuppressDiagnosticWarning_NoWarning

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

            container.Register<IPlugin, DisposablePlugin>();

            Registration registration = container.GetRegistration(typeof(IPlugin)).Registration;

            registration.SuppressDiagnosticWarning(DiagnosticType.DisposableTransientComponent);

            container.Verify();

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

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

示例4: GetInstance_TypeWithContextMultipleLevelsWithAllSingletons_GetsInjectedWithExpectedContext

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

            container.RegisterWithContext<IContextualLogger>(context => new ContextualLogger(context));

            container.Register<IRepository, RepositoryThatDependsOnLogger>(Lifestyle.Singleton);

            container.Register<IService, ServiceThatDependsOnRepository>(Lifestyle.Singleton);

            container.GetRegistration(typeof(IRepository)).Registration.SuppressDiagnosticWarning(
                DiagnosticType.PotentialLifestyleMismatch, "Depending on ContextualLogger is fine.");

            container.GetRegistration(typeof(IService)).Registration.SuppressDiagnosticWarning(
                DiagnosticType.PotentialLifestyleMismatch, "Depending on ContextualLogger is fine.");

            // Act
            var service = container.GetInstance<IService>() as ServiceThatDependsOnRepository;

            // Assert
            var logger = service.InjectedRepository.Logger;

            Assert.AreEqual(typeof(IRepository), logger.Context.ServiceType);
            Assert.AreEqual(typeof(RepositoryThatDependsOnLogger), logger.Context.ImplementationType);
        }
开发者ID:MichaelSagalovich,项目名称:SimpleInjector,代码行数:26,代码来源:ContextDependentExtensionsTests.cs

示例5: Verify_NestedDepenencyWithScopedLifestyleWithCustomBuiltExpression_Succeeds

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

            container.Options.DefaultScopedLifestyle = new LifetimeScopeLifestyle();

            // class RealUserService(IUserRepository)
            container.Register<UserServiceBase, RealUserService>(Lifestyle.Transient);
            container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

            container.Register<object>(() =>
            {
                var expression = container.GetRegistration(typeof(UserServiceBase)).BuildExpression();

                // By building this expression we circumvent the container's scope optimizations and we force
                // a different path through the code causing Scope.GetScopelessInstance to be called.
                var userServiceFactory = Expression.Lambda<Func<UserServiceBase>>(expression).Compile();

                return userServiceFactory();
            }, Lifestyle.Singleton);

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

示例6: CustomBuiltDelegate_NestedDepenencyWithScopedLifestyle_ThrowsExpectedException

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

            container.Options.DefaultScopedLifestyle = new LifetimeScopeLifestyle();

            // class RealUserService(IUserRepository)
            container.Register<UserServiceBase, RealUserService>(Lifestyle.Transient);
            container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

            var expression = container.GetRegistration(typeof(UserServiceBase)).BuildExpression();

            // By building this expression we circumvent the container's scope optimizations and we force
            // a different path through the code causing Scope.GetScopelessInstance to be called.
            var userServiceFactory = Expression.Lambda<Func<UserServiceBase>>(expression).Compile();

            // Act
            Action action = () => userServiceFactory();

            // Assert
            AssertThat.ThrowsWithExceptionMessageContains<ActivationException>(
                "the instance is requested outside the context of a Lifetime Scope",
                action);
        }
开发者ID:MichaelSagalovich,项目名称:SimpleInjector,代码行数:25,代码来源:LifestyleScopedTests.cs

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

示例8: VisualizeObjectGraph_WhenCalledBeforeInstanceIsCreated_ThrowsAnInvalidOperationException

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

            container.Register<RealTimeProvider>();

            InstanceProducer producer = container.GetRegistration(typeof(RealTimeProvider));

            // Act
            Action action = () => producer.VisualizeObjectGraph();

            // Assert
            AssertThat.Throws<InvalidOperationException>(action,
                "When the instance hasn't been created or the Expression hasn't been built, there's not yet " +
                "enough information to visualize the object graph. Instead of returning an incorrect result " +
                "we expect the library to throw an exception here.");
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:18,代码来源:InstanceProducerTests.cs

示例9: GetValidRelationship

        private static KnownRelationship GetValidRelationship()
        {
            var container = new Container();

            var dummyRegistration = container.GetRegistration(typeof(Container));

            return new KnownRelationship(typeof(object), Lifestyle.Transient, dummyRegistration);
        }
开发者ID:virasak,项目名称:SimpleInjector,代码行数:8,代码来源:DecoratorCollectionTests.cs

示例10: BuildNewExpression

        private static NewExpression BuildNewExpression(Container container, 
            ConstructorInfo constructor, 
            ParameterExpression[] funcParameterExpression)
        {
            var ctorParameters = constructor.GetParameters();
            var ctorParameterTypes = ctorParameters.Select(p => p.ParameterType).ToArray();
            var funcParameterTypes = funcParameterExpression.Select(p => p.Type).ToArray();

            int funcParametersIndex = IndexOfSubCollection(ctorParameterTypes, funcParameterTypes);

            if (funcParametersIndex == -1)
            {
                throw new ActivationException(string.Format(CultureInfo.CurrentCulture,
                    "The constructor of type {0} did not contain the sequence of the following " +
                    "constructor parameters: {1}.",
                    constructor.DeclaringType.FullName,
                    string.Join(", ", funcParameterTypes.Select(t => t.Name))));
            }

            var firstCtorParameterExpressions = ctorParameterTypes
                .Take(funcParametersIndex)
                .Select(type => container.GetRegistration(type, true).BuildExpression());

            var lastCtorParameterExpressions = ctorParameterTypes
                .Skip(funcParametersIndex + funcParameterTypes.Length)
                .Select(type => container.GetRegistration(type, true).BuildExpression());

            var expressions = firstCtorParameterExpressions
                .Concat(funcParameterExpression)
                .Concat(lastCtorParameterExpressions)
                .ToArray();

            return Expression.New(constructor, expressions);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:34,代码来源:ResolvingFactoriesExtensions.cs

示例11: GetInstance_OpenGenericRegistration_CallsInstanceCreated

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

            var container = new Container();

            container.Register(typeof(IValidate<>), typeof(NullValidator<>));

            container.RegisterInitializer(actualContexts.Add, TruePredicate);

            // Act
            var instance = container.GetInstance<IValidate<int>>();

            // Assert
            Assert.AreEqual(1, actualContexts.Count);

            Assert.AreEqual(
                expected: container.GetRegistration(typeof(IValidate<int>)).Registration,
                actual: actualContexts.First().Context.Registration);

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

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

示例13: GetInstance_OnRegisteredConcreteTransientTypeWithoutDependencies_CallsInstanceCreatedWithExpectedType

        public void GetInstance_OnRegisteredConcreteTransientTypeWithoutDependencies_CallsInstanceCreatedWithExpectedType()
        {
            // Registration
            var actualContexts = new List<InstanceInitializationData>();

            var container = new Container();

            container.Register<RealTimeProvider>();

            container.RegisterInitializer(actualContexts.Add, TruePredicate);

            // Act
            object instance = container.GetInstance<RealTimeProvider>();

            // Assert
            var actualContext = actualContexts.First().Context;

            Assert.AreSame(container.GetRegistration(typeof(RealTimeProvider)), actualContext.Producer);
            Assert.AreSame(container.GetRegistration(typeof(RealTimeProvider)).Registration, actualContext.Registration);
            Assert.AreSame(instance, actualContexts.First().Instance);
        }
开发者ID:khellang,项目名称:SimpleInjector,代码行数:21,代码来源:RegisterContextualInitializerTests.cs

示例14: GetInstanceProducerForConsumer

        private static InstanceProducer GetInstanceProducerForConsumer()
        {
            var container = new Container();

            container.Register<Consumer>();

            container.Verify();

            var registration = container.GetRegistration(typeof(Consumer));
            return registration;
        }
开发者ID:MichaelSagalovich,项目名称:SimpleInjector,代码行数:11,代码来源:InstanceProducerInlineVisualizerTests.cs

示例15: Analyze_OneViolationWithSuppressDiagnosticWarningOnTheOtherRegistration_OneWarning

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

            container.Register<IFoo, FooBar>(new LifetimeScopeLifestyle());
            container.Register<IBar, FooBar>(new LifetimeScopeLifestyle());

            container.Verify(VerificationOption.VerifyOnly);

            var registration = container.GetRegistration(typeof(IBar)).Registration;

            registration.SuppressDiagnosticWarning(DiagnosticType.TornLifestyle);

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

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


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