Beispiel #1
0
        public void GetInstance_EventRegisteredForNonRootTypeThatThrowsException_ThrowsAnDescriptiveException()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register <UserServiceBase, RealUserService>();

            container.ResolveUnregisteredType += (s, e) =>
            {
                e.Register(() => { throw new Exception(); });
            };

            try
            {
                // Act
                container.GetInstance <UserServiceBase>();

                // Assert
                Assert.Fail("Exception was expected.");
            }
            catch (Exception ex)
            {
                const string AssertMessage = "Exception message was not descriptive.";

                AssertThat.ExceptionMessageContains(
                    "registered delegate for type UserServiceBase threw an exception", ex,
                    AssertMessage);
            }
        }
        public void GetInstance_EventRegisteredThatReturnsNull_ThrowsExceptionWithExpectedMessage()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.ResolveUnregisteredType += (s, e) =>
            {
                e.Register(() => null);
            };

            try
            {
                // Act
                container.GetInstance <IUserRepository>();

                // Assert
                Assert.Fail("Exception was expected.");
            }
            catch (Exception ex)
            {
                const string AssertMessage = "Exception message was not descriptive. Actual message: ";

                AssertThat.ExceptionMessageContains(
                    "registered delegate for type IUserRepository returned null", ex, AssertMessage);
            }
        }
        public void GetInstance_ExpressionBuildingChangedTheRegisterSingleRegistrationToReturnNull_ThrowsExpectedException()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Register <IUserRepository, SqlUserRepository>(Lifestyle.Singleton);

            container.ExpressionBuilding += (s, e) =>
            {
                e.Expression = Expression.Constant(null, typeof(SqlUserRepository));
            };

            try
            {
                // Act
                container.GetInstance(typeof(IUserRepository));

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ActivationException ex)
            {
                AssertThat.ExceptionMessageContains(
                    "The registered delegate for type SqlUserRepository returned null.", ex);
            }
        }
        public void GetInstance_ExpressionBuildingEventChangesTheTypeOfTheExpression_ThrowsExpressiveExceptionWhenApplyingInitializer()
        {
            // Arrange
            var container = ContainerFactory.New();

            // Register a transient instance
            container.Register <IUserRepository, SqlUserRepository>();

            container.RegisterInitializer <object>(instance => { });

            container.ExpressionBuilding += (sender, e) =>
            {
                if (e.RegisteredServiceType == typeof(IUserRepository))
                {
                    // Replace the expression with a different type (this is incorrect behavior).
                    e.Expression = Expression.Constant(new InMemoryUserRepository());
                }
            };

            try
            {
                // Act
                container.GetInstance <IUserRepository>();

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ActivationException ex)
            {
                AssertThat.ExceptionMessageContains(
                    "The initializer(s) for type SqlUserRepository could not be applied.", ex);
            }
        }
Beispiel #5
0
        public void GetInstance_UnregisteredConcreteTypeWithUnregistedDependencies_ThrowsExpectedException()
        {
            // Arrange
            string expectedMessage = @"
                No registration for type RealUserService could be found and an implicit registration could not 
                be made. The constructor of type RealUserService contains the parameter of type 
                IUserRepository with name 'repository' that is not registered. Please ensure IUserRepository 
                is registered in the container, or change the constructor of RealUserService."
                                     .TrimInside();

            // We don't register the required IUserRepository dependency.
            var container = ContainerFactory.New();

            try
            {
                // Act
                // RealUserService is a concrete class with a constructor with a single argument of type
                // IUserRepository.
                container.GetInstance <RealUserService>();

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (Exception ex)
            {
                AssertThat.ExceptionMessageContains(expectedMessage, ex);
            }
        }
Beispiel #6
0
        public void PropertyInjectionBehavior_ChangedAfterFirstRegistration_Fails()
        {
            // Arrange
            var expectedBehavior = new AlternativePropertySelectionBehavior();

            var options = new ContainerOptions();

            var container = new Container(options);

            container.RegisterSingle <object>("The first registration.");

            try
            {
                // Act
                options.PropertySelectionBehavior = expectedBehavior;

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (InvalidOperationException ex)
            {
                AssertThat.ExceptionMessageContains(
                    "PropertySelectionBehavior property cannot be changed after the first registration",
                    ex);
            }
        }
        public void GetRegistration_Always_LocksTheContainer3()
        {
            // Arrange
            var container = ContainerFactory.New();

            try
            {
                container.GetRegistration(typeof(ITimeProvider), throwOnFailure: true);
            }
            catch
            {
                // Exception expected.
            }

            try
            {
                // Act
                container.Register <ITimeProvider, RealTimeProvider>();

                // Assert
                Assert.Fail("The container should get locked during the call to GetRegistration, because a " +
                            "user can call the GetInstance() and BuildExpression() methods on the returned instance. " +
                            "BuildExpression can internally call GetInstance and the first call to GetInstance should " +
                            "always lock the container for reasons of correctness.");
            }
            catch (InvalidOperationException ex)
            {
                AssertThat.ExceptionMessageContains("container can't be changed", ex);
            }
        }
        public void GetInstance_EventRegisteredWithInvalidExpression_ThrowsAnDescriptiveException()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.ResolveUnregisteredType += (s, e) =>
            {
                var invalidExpression = Expression.GreaterThan(Expression.Constant(1), Expression.Constant(1));

                e.Register(invalidExpression);
            };

            try
            {
                // Act
                container.GetInstance <IUserRepository>();

                // Assert
                Assert.Fail("Exception was expected.");
            }
            catch (Exception ex)
            {
                const string AssertMessage = "Exception message was not descriptive enough.";

                AssertThat.ExceptionMessageContains(
                    "Error occurred while trying to build a delegate for type", ex, AssertMessage);
                AssertThat.ExceptionMessageContains(
                    "Expression of type 'System.Boolean' cannot be used for return type", ex, AssertMessage);
            }
        }
        public void BuildExpression_ReturningNull_ContainerWillThrowAnExpressiveExceptionMessage()
        {
            // Arrange
            var container = ContainerFactory.New();

            var invalidLifestyle = new FakeLifestyle();

            var invalidRegistration = new FakeRegistration(invalidLifestyle, container, typeof(RealTimeProvider))
            {
                ExpressionToReturn = null
            };

            invalidLifestyle.RegistrationToReturn = invalidRegistration;

            container.Register <ITimeProvider, RealTimeProvider>(invalidLifestyle);

            try
            {
                // Act
                container.GetInstance <ITimeProvider>();

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ActivationException ex)
            {
                AssertThat.ExceptionMessageContains(
                    "The FakeRegistration for the FakeLifestyle returned a null reference " +
                    "from its BuildExpression method.", ex);
            }
        }
        public void GetInstance_ExpressionBuildingChangedExpressionInAnIncompatibleWay_ThrowsExpectedException()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.RegisterSingle <IUserRepository, SqlUserRepository>();

            container.ExpressionBuilding += (s, e) =>
            {
                e.Expression = Expression.Constant("some string", typeof(string));
            };

            try
            {
                // Act
                container.GetInstance(typeof(IUserRepository));

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ActivationException ex)
            {
                AssertThat.ExceptionMessageContains(
                    "Error occurred while trying to build a delegate for type IUserRepository using " +
                    "the expression", ex);
            }
        }
        public void GetRegistration_UnregisteredConcreteTypeWithConstructorWithInvalidArguments_ThrowsExpectedException()
        {
            // Arrange
            var container = ContainerFactory.New();

            try
            {
                // Act
                container.GetRegistration(typeof(RealUserService), throwOnFailure: true);

                // Assert
                Assert.Fail("Because we did not register the IUserRepository interface, " +
                            "GetRegistration should fail.");
            }
            catch (ActivationException ex)
            {
                string message = ex.Message;

                AssertThat.ExceptionMessageContains(typeof(RealUserService).Name, ex,
                                                    "The exception message should contain the name of the type.");

                AssertThat.ExceptionMessageContains(typeof(IUserRepository).Name, ex,
                                                    "The exception message should contain the missing constructor argument.");

                AssertThat.ExceptionMessageContains(
                    "For IUserRepository to be resolved, it must be registered in the container",
                    ex, "(1) The exception message should give a solution to solve the problem.");

                AssertThat.ExceptionMessageContains(@"
                    For IUserRepository to be resolved, it must be registered in the container"
                                                    .TrimInside(),
                                                    ex,
                                                    "(2) The exception message should give a solution to solve the problem.");
            }
        }
        private static void Assert_RegistrationFailsWithExpectedAmbiguousMessage(string typeName, Action action)
        {
            try
            {
                // Act
                action();

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ArgumentException ex)
            {
                string message = @"
                    You are trying to register " + typeName + @" as a service type, but registering this type
                    is not allowed to be registered because the type is ambiguous";

                AssertThat.ExceptionMessageContains(message.TrimInside(), ex);
            }
        }
Beispiel #13
0
        public void ExpressionBuilt_CalledAfterACallToVerify_FailsWithTheExpectedMessage()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Verify();

            try
            {
                // Act
                container.ExpressionBuilt += (s, e) => { };

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (InvalidOperationException ex)
            {
                AssertThat.ExceptionMessageContains("The container can't be changed", ex);
            }
        }
Beispiel #14
0
        public void AllowOverridingRegistrations_SetToFalse_ContainerThrowsExpectedExceptionMessage()
        {
            // Arrange
            var container = new Container();

            container.Options.AllowOverridingRegistrations = false;

            container.Register <IUserRepository, SqlUserRepository>();

            try
            {
                // Act
                container.Register <IUserRepository, InMemoryUserRepository>();
            }
            catch (InvalidOperationException ex)
            {
                // Assert
                AssertThat.ExceptionMessageContains("Container.Options.AllowOverridingRegistrations", ex);
            }
        }
Beispiel #15
0
        public void GetInstance_OnConcreteTypeWithStringConstructorArgument_FailsWithExpectedException()
        {
            // Arrange
            string expectedMessage = typeof(ConcreteTypeWithStringConstructorArgument).Name + " contains pa" +
                                     "rameter 'stringParam' of type String which can not be used for constructor injection.";

            var container = ContainerFactory.New();

            try
            {
                // Act
                container.GetInstance <ConcreteTypeWithStringConstructorArgument>();

                // Assert
                Assert.Fail("The call was expected to fail.");
            }
            catch (ActivationException ex)
            {
                AssertThat.ExceptionMessageContains(expectedMessage, ex);
            }
        }
Beispiel #16
0
        public void ContainerWithOptions_SuppliedWithAnInstanceThatAlreadyBelongsToAnotherContainer_ThrowsExpectedException()
        {
            // Arrange
            var options = new ContainerOptions();

            var container1 = new Container(options);

            try
            {
                // Act
                new Container(options);

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (ArgumentException ex)
            {
                AssertThat.ExceptionMessageContains(
                    "supplied ContainerOptions instance belongs to another Container instance.", ex);
            }
        }
        public void Register_AbstractTypeWithSinglePublicConstructor_ThrowsExpectedException()
        {
            // Arrange
            string expectedMessage = @"
                The given type RegisterConcreteTests.AbstractTypeWithSinglePublicConstructor is not a concrete
                type. Please use one of the other overloads to register this type.
                ".TrimInside();

            var container = ContainerFactory.New();

            try
            {
                // Act
                container.Register <AbstractTypeWithSinglePublicConstructor>();

                Assert.Fail("The abstract type was not expected to be registered successfully.");
            }
            catch (ArgumentException ex)
            {
                AssertThat.ExceptionMessageContains(expectedMessage, ex);
            }
        }
        public void GetInstance_DelegateReturningNullRegisteredUsingRegisterSingleByFuncOfNonRootType_ThrowsActivationExceptionWithExpectedExceptionMessage()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.RegisterSingle <IUserRepository>(() => null);

            try
            {
                // Act
                container.GetInstance <RealUserService>();

                // Assert
                Assert.Fail("The GetInstance method was expected to fail, because of the faulty registration.");
            }
            catch (ActivationException ex)
            {
                string expectedMessage = "The registered delegate for type IUserRepository returned null.";

                AssertThat.ExceptionMessageContains(expectedMessage, ex);
            }
        }
Beispiel #19
0
        public void Register_WithAnOverrideCalledAfterACallToVerify_FailsWithTheExpectedException()
        {
            // Arrange
            var container = ContainerFactory.New();

            container.Options.AllowOverridingRegistrations = true;

            container.Register <IUserRepository, SqlUserRepository>();

            container.Verify();

            try
            {
                // Act
                container.Register <IUserRepository, SqlUserRepository>(Lifestyle.Singleton);

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (InvalidOperationException ex)
            {
                AssertThat.ExceptionMessageContains("The container can't be changed", ex);
            }
        }
Beispiel #20
0
        public void GetInstance_UnregisteredConcreteTypeWithConstructorWithInvalidArguments_ThrowsException()
        {
            // Arrange
            var container = ContainerFactory.New();

            try
            {
                // Act
                container.GetInstance <RealUserService>();

                // Assert
                Assert.Fail("Because we did not register the IUserRepository interface, " +
                            "GetInstance<RealUserService> should fail.");
            }
            catch (ActivationException ex)
            {
                string message = ex.Message;

                AssertThat.ExceptionMessageContains(typeof(RealUserService).Name, ex,
                                                    "The exception message should contain the name of the type.");

                AssertThat.ExceptionMessageContains(typeof(IUserRepository).Name, ex,
                                                    "The exception message should contain the missing constructor argument.");

                AssertThat.ExceptionMessageContains(
                    "Please ensure IUserRepository is registered in the container",
                    ex, "(1) The exception message should give a solution to solve the problem.");

                AssertThat.ExceptionMessageContains(@"
                    Please ensure IUserRepository is registered in the container,
                    or change the constructor of RealUserService"
                                                    .TrimInside(),
                                                    ex,
                                                    "(2) The exception message should give a solution to solve the problem.");
            }
        }