public void LifetimeScopeDispose_WithWhenScopeEndsRegistration_CallsTheRegisteredAction()
        {
            // Arrange
            int actionCallCount = 0;

            var container = new Container();

            var lifestyle = new LifetimeScopeLifestyle();

            container.Register <DisposableCommand, DisposableCommand>(lifestyle);

            container.RegisterInitializer <DisposableCommand>(command =>
            {
                lifestyle.WhenScopeEnds(container, () => { actionCallCount++; });
            });

            using (container.BeginLifetimeScope())
            {
                container.GetInstance <DisposableCommand>();

                // Act
            }

            // Assert
            Assert.AreEqual(1, actionCallCount, "Delegate is expected to be called exactly once.");
        }
        public void Analyze_TwoRegistrationsWithMultipleInstancesOfTheSameLifestyle_GivesNoWarning()
        {
            // Arrange
            var container = new Container();

            var scopedFooBar1 = new LifetimeScopeLifestyle().CreateRegistration <FooBar>(container);
            var scopedFooBar2 = new LifetimeScopeLifestyle().CreateRegistration <FooBar>(container);

            container.AddRegistration(typeof(IFoo), scopedFooBar1);
            container.AddRegistration(typeof(IBar), scopedFooBar1);
            container.AddRegistration(typeof(IFooExt), scopedFooBar2);
            container.AddRegistration(typeof(IBarExt), scopedFooBar2);

            container.Verify(VerificationOption.VerifyOnly);

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

            // Assert
            Assert.IsFalse(results.Any(),
                           "Diagnostics should be performed on the lifestyle's type, not on the instance because the " +
                           "user is allowed to create multiple instances of the same lifestyle object. Actual: " +
                           Actual(results));
        }
        public void LifetimeScopeDispose_TwoScopedRegistationsForTheSameServiceType_DisposesBothInstances()
        {
            // Arrange
            var disposedInstances = new HashSet <object>();

            var lifestyle = new LifetimeScopeLifestyle();

            var container = new Container();

            var reg1 = lifestyle.CreateRegistration <ICommand, DisposableCommand>(container);
            var reg2 = lifestyle.CreateRegistration <ICommand, DisposableCommand>(container);

            container.AppendToCollection(typeof(ICommand), reg1);
            container.AppendToCollection(typeof(ICommand), reg2);

            using (container.BeginLifetimeScope())
            {
                var commands = container.GetAllInstances <ICommand>().Cast <DisposableCommand>().ToArray();

                Assert.AreNotSame(commands[0], commands[1], "Test setup failed.");

                commands[0].Disposing += sender => disposedInstances.Add(sender);
                commands[1].Disposing += sender => disposedInstances.Add(sender);

                // Act
            }

            // Assert
            Assert.AreEqual(2, disposedInstances.Count, "Two instances were expected to be disposed.");
        }
        public void LifetimeScopeDispose_WithWhenScopeEndsRegistration_CallsTheRegisteredActionBeforeCallingDispose()
        {
            // Arrange
            bool delegateHasBeenCalled          = false;
            DisposableCommand instanceToDispose = null;

            var container = new Container();

            var lifestyle = new LifetimeScopeLifestyle();

            container.Register <DisposableCommand, DisposableCommand>(lifestyle);

            container.RegisterInitializer <DisposableCommand>(command =>
            {
                LifetimeScopeLifestyle.WhenCurrentScopeEnds(container, () =>
                {
                    Assert.IsFalse(command.HasBeenDisposed,
                                   "The action should be called before disposing the instance, because users are " +
                                   "to use those instances.");
                    delegateHasBeenCalled = true;
                });
            });

            using (container.BeginLifetimeScope())
            {
                instanceToDispose = container.GetInstance <DisposableCommand>();

                // Act
            }

            // Assert
            Assert.IsTrue(delegateHasBeenCalled, "Delegate is expected to be called.");
        }
        public static Container GetScopedContainer()
        {
            var container = new Container();
            var lifestyle = new LifetimeScopeLifestyle();

            container.RegisterDependencies(lifestyle);
            return(container);
        }
Пример #6
0
        /// <summary>
        /// Registers that a single instance of <typeparamref name="TConcrete"/> will be returned for
        /// each lifetime scope that has been started using
        /// <see cref="BeginLifetimeScope">BeginLifetimeScope</see>. When the
        /// lifetime scope is disposed and <typeparamref name="TConcrete"/> implements <see cref="IDisposable"/>,
        /// the cached instance will be disposed as well.
        /// Scopes can be nested, and each scope gets its own instance.
        /// </summary>
        /// <typeparam name="TConcrete">The concrete type that will be registered.</typeparam>
        /// <param name="container">The container to make the registrations in.</param>
        /// <param name="disposeWhenLifetimeScopeEnds">If set to <c>true</c> the cached instance will be
        /// disposed at the end of its lifetime.</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when the <paramref name="container"/> is a null reference.</exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when this container instance is locked and can not be altered, or when an
        /// the <typeparamref name="TConcrete"/> has already been registered.
        /// </exception>
        /// <exception cref="ArgumentException">Thrown when the <typeparamref name="TConcrete"/> is a type
        /// that can not be created by the container.</exception>
        public static void RegisterLifetimeScope <TConcrete>(this Container container,
                                                             bool disposeWhenLifetimeScopeEnds)
            where TConcrete : class, IDisposable
        {
            Requires.IsNotNull(container, "container");

            container.Register <TConcrete, TConcrete>(LifetimeScopeLifestyle.Get(disposeWhenLifetimeScopeEnds));
        }
Пример #7
0
        /// <summary>
        /// Registers that a single instance of <typeparamref name="TImplementation"/> will be returned for
        /// each lifetime scope that has been started using
        /// <see cref="BeginLifetimeScope">BeginLifetimeScope</see>.  When the lifetime scope is disposed,
        /// <paramref name="disposeWhenLifetimeScopeEnds"/> is set to <b>true</b>, and the cached instance
        /// implements <see cref="IDisposable"/>, that cached instance will be disposed as well.
        /// Scopes can be nested, and each scope gets its own instance.
        /// </summary>
        /// <typeparam name="TService">The interface or base type that can be used to retrieve the instances.</typeparam>
        /// <typeparam name="TImplementation">The concrete type that will be registered.</typeparam>
        /// <param name="container">The container to make the registrations in.</param>
        /// <param name="disposeWhenLifetimeScopeEnds">If set to <c>true</c> the cached instance will be
        /// disposed at the end of its lifetime.</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when the <paramref name="container"/> is a null reference.</exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when this container instance is locked and can not be altered, or when an
        /// the <typeparamref name="TService"/> has already been registered.</exception>
        /// <exception cref="ArgumentException">Thrown when the given <typeparamref name="TImplementation"/>
        /// type is not a type that can be created by the container.
        /// </exception>
        public static void RegisterLifetimeScope <TService, TImplementation>(
            this Container container, bool disposeWhenLifetimeScopeEnds)
            where TImplementation : class, TService, IDisposable
            where TService : class
        {
            Requires.IsNotNull(container, "container");

            container.Register <TService, TImplementation>(LifetimeScopeLifestyle.Get(disposeWhenLifetimeScopeEnds));
        }
Пример #8
0
        /// <summary>
        /// Registers the specified delegate that allows returning instances of <typeparamref name="TService"/>,
        /// and returned instances are cached during the lifetime of a given scope that has been started using
        /// <see cref="BeginLifetimeScope">BeginLifetimeScope</see>. When the lifetime scope is disposed,
        /// <paramref name="disposeWhenLifetimeScopeEnds"/> is set to <b>true</b>, and the cached instance
        /// implements <see cref="IDisposable"/>, that cached instance will be disposed as well.
        /// Scopes can be nested, and each scope gets its own instance.
        /// </summary>
        /// <typeparam name="TService">The interface or base type that can be used to retrieve instances.</typeparam>
        /// <param name="container">The container to make the registrations in.</param>
        /// <param name="instanceCreator">The delegate that allows building or creating new instances.</param>
        /// <param name="disposeWhenLifetimeScopeEnds">If set to <c>true</c> the cached instance will be
        /// disposed at the end of its lifetime.</param>
        /// <exception cref="ArgumentNullException">
        /// Thrown when either the <paramref name="container"/>, or <paramref name="instanceCreator"/> are
        /// null references.</exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown when this container instance is locked and can not be altered, or when the
        /// <typeparamref name="TService"/> has already been registered.</exception>
        public static void RegisterLifetimeScope <TService>(this Container container,
                                                            Func <TService> instanceCreator, bool disposeWhenLifetimeScopeEnds)
            where TService : class
        {
            Requires.IsNotNull(container, "container");
            Requires.IsNotNull(instanceCreator, "instanceCreator");

            container.Register <TService>(instanceCreator, LifetimeScopeLifestyle.Get(disposeWhenLifetimeScopeEnds));
        }
    public static void Configure(Container container)
    {
        var lifetimeScope = new LifetimeScopeLifestyle();

        container.Register <IUnitOfWork, UnitOfWork>(lifetimeScope);
        container.RegisterManyForOpenGeneric(
            typeof(IRepository <>),
            lifetimeScope,
            typeof(IRepository <>).Assembly);
    }
Пример #10
0
        public static Container GetContainer()
        {
            var container       = new Container();
            var scopedLifestyle = new LifetimeScopeLifestyle();

            container.RegisterPersistenceDependencies(scopedLifestyle);
            container.RegisterModelDependencies(scopedLifestyle);

            return(container);
        }
        public void WhenScopeEnds_NullContainerArgument_ThrowsException()
        {
            // Arrange
            var lifestyle = new LifetimeScopeLifestyle();

            // Act
            Action action = () => lifestyle.WhenScopeEnds(null, () => { });

            // Assert
            AssertThat.Throws <ArgumentNullException>(action);
        }
Пример #12
0
        public void DefaultScopedLifestyle_ChangedBeforeAnyRegistrations_ChangesThePropertyToTheSetInstance()
        {
            // Arrange
            var expectedLifestyle = new LifetimeScopeLifestyle();

            var options = GetContainerOptions();

            // Act
            options.DefaultScopedLifestyle = expectedLifestyle;

            // Assert
            Assert.AreSame(expectedLifestyle, options.DefaultScopedLifestyle,
                           "The set_DefaultScopedLifestyle did not work.");
        }
        public void DefaultLifestyle_ChangedMultipleTimesBeforeAnyRegistrations_ChangesThePropertyToTheSetInstance()
        {
            // Arrange
            var expectedLifestyle = new LifetimeScopeLifestyle();

            var options = GetContainerOptions();

            // Act
            options.DefaultLifestyle = Lifestyle.Singleton;
            options.DefaultLifestyle = Lifestyle.Transient;

            // Assert
            Assert.AreSame(Lifestyle.Transient, options.DefaultLifestyle,
                           "The set_DefaultLifestyle did not work.");
        }
        private void RegisterChild()
        {
            var scopedLifestyle = new LifetimeScopeLifestyle();

            this.scopedRegistrations[typeof(ICombined1)] = Lifestyle.Transient.CreateProducer <ICombined1>(
                () => new ScopedCombined1(new ScopedTransient(), this.container.GetInstance <ISingleton1>()),
                this.container);

            this.scopedRegistrations[typeof(ICombined2)] = Lifestyle.Transient.CreateProducer <ICombined2>(
                () => new ScopedCombined2(new ScopedTransient(), this.container.GetInstance <ISingleton1>()),
                this.container);

            this.scopedRegistrations[typeof(ICombined3)] = Lifestyle.Transient.CreateProducer <ICombined3>(
                () => new ScopedCombined3(new ScopedTransient(), this.container.GetInstance <ISingleton1>()),
                this.container);
        }
Пример #15
0
        public void ScopedProxyLifestyleCreateRegistration_Always_WrapsTheScopeOfDefaultScopedLifestyle()
        {
            // Arrange
            var expectedLifestyle = new LifetimeScopeLifestyle();

            var container = new Container();

            container.Options.DefaultScopedLifestyle = expectedLifestyle;

            // Act
            var registration = Lifestyle.Scoped.CreateRegistration(typeof(NullLogger), container);

            var actualLifestyle = registration.Lifestyle;

            // Assert
            Assert.AreSame(expectedLifestyle, actualLifestyle);
        }
        public void Verify_WithWhenScopeEndsRegistration_Succeeds()
        {
            // Arrange
            var container = new Container();

            var lifestyle = new LifetimeScopeLifestyle();

            container.Register <ICommand, DisposableCommand>(lifestyle);

            container.RegisterInitializer <DisposableCommand>(command =>
            {
                lifestyle.WhenScopeEnds(container, () => { });
            });

            // Act
            container.Verify();
        }
Пример #17
0
        private static void RegisterDataServices(this Container container, string connectionString)
        {
            var scopedLifestyle             = new LifetimeScopeLifestyle();
            var databaseContextRegistration = scopedLifestyle.CreateRegistration(() =>
            {
#if DEBUG
                Database.SetInitializer(new DropCreateDatabaseIfModelChangesInitializer());
#else
                Database.SetInitializer <HiLaarischEntities>(null);
#endif
                return(new HiLaarischEntities(connectionString));
            }, container);

            container.AddRegistration(typeof(HiLaarischEntities), databaseContextRegistration);
            container.AddRegistration(typeof(DbContext), databaseContextRegistration);

            container.Register(typeof(IRepository <>), typeof(Repository <>));
        }
Пример #18
0
        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);
        }
Пример #19
0
        public static void Configure(Container container)
        {
            var lifetimeScope = new LifetimeScopeLifestyle();

            //container.Register<IUnitOfWork, UnitOfWork>(lifetimeScope);

            //container.RegisterManyForOpenGeneric(
            //    typeof(IRepository<>),
            //    lifetimeScope,
            //    typeof(IRepository<>).Assembly);
            container.Register <IActionRepository, ActionRepository>();
            container.Register <IUserRepository, UserRepository>();
            container.Register <IObjectContextFactory, ObjectContextFactory>();
            container.Register <IContactRepository, ContactRepository>();
            container.Register <ITagRepository, TagRepository>();
            container.Register <IAccountRepository, AccountRepository>();
            container.Register <ITourRepository, TourRepository>();
            container.Register <INoteRepository, NoteRepository>();
            container.Register <IUnitOfWork, DatabaseUnitOfWork>(Lifestyle.Singleton);
            container.Register <ICommunicationRepository, CommunicationRepository>();


            container.Register <IAttachmentRepository, AttachmentRepository>();


            container.Register <ICampaignRepository, CampaignRepository>();

            container.Register <ICommunicationLogInDetailRepository, CommunicationLogInDetailRepository>();

            //var services = GlobalConfiguration.Configuration.Services;
            //var controllerTypes = services.GetHttpControllerTypeResolver()
            //    .GetControllerTypes(services.GetAssembliesResolver());

            //foreach (var controllerType in controllerTypes)
            //{
            //    container.Register(controllerType);
            //}

            //container.Verify();
            //GlobalConfiguration.Configuration.DependencyResolver =
            //        new SimpleInjectorWebApiDependencyResolver(container);
            IoC.Container = container;
        }
    public static void Configure(Container container)
    {
        var lifetimeScope = new LifetimeScopeLifestyle();

        container.Register <IUnitOfWork, UnitOfWork>(lifetimeScope);
        //this query needs improvement
        var registrations =
            from type in typeof(IRepository <>).Assembly.GetExportedTypes()
            where typeof(IRepository).IsAssignableFrom(type) &&
            type.IsClass &&
            !type.IsAbstract
            from service in type.GetInterfaces()
            where service.IsGenericType
            select new { Service = service, Implementation = type };

        foreach (var registration in registrations)
        {
            container.Register(registration.Service,
                               registration.Implementation, lifetimeScope);
        }
    }
        public void LifetimeScope_TwoScopedRegistationsForTheSameServiceType_CreatesTwoInstances()
        {
            // Arrange
            var lifestyle = new LifetimeScopeLifestyle();

            var container = new Container();

            var reg1 = lifestyle.CreateRegistration <ICommand, DisposableCommand>(container);
            var reg2 = lifestyle.CreateRegistration <ICommand, DisposableCommand>(container);

            container.AppendToCollection(typeof(ICommand), reg1);
            container.AppendToCollection(typeof(ICommand), reg2);

            using (container.BeginLifetimeScope())
            {
                // Act
                var commands = container.GetAllInstances <ICommand>().Cast <DisposableCommand>().ToArray();

                // Assert
                Assert.AreNotSame(commands[0], commands[1], "Two instances were expected.");
            }
        }
        public void Analyze_FourProducersForTwoRegistrationsWithDifferentLifestylesForTheSameImplementation_ReturnsExpectedWarnings()
        {
            // Arrange
            string expectedMessage1 = @"
                The registration for IFoo (Lifetime Scope) maps to the same implementation (FooBar) as the 
                registrations for IFooExt (Singleton) and IBarExt (Singleton) do"
                                      .TrimInside();

            string expectedMessage2 = @"
                The registration for IFooExt (Singleton) maps to the same implementation (FooBar) as the 
                registrations for IFoo (Lifetime Scope) and IBar (Lifetime Scope) do"
                                      .TrimInside();

            var container = new Container();

            var transientFooBar = new LifetimeScopeLifestyle().CreateRegistration <FooBar>(container);
            var singletonFooBar = Lifestyle.Singleton.CreateRegistration <FooBar>(container);

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

            container.AddRegistration(typeof(IFooExt), singletonFooBar);
            container.AddRegistration(typeof(IBarExt), singletonFooBar);

            container.Verify(VerificationOption.VerifyOnly);

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

            // Assert
            Assert.AreEqual(4, results.Length, Actual(results));
            Assert_ContainsDescription(results, expectedMessage1);
            Assert_ContainsDescription(results, expectedMessage2);
            Assert_AllOfType <AmbiguousLifestylesDiagnosticResult>(results);
        }
        public void LifetimeScopeDispose_WithTransientRegisteredForDisposal_DisposesThatInstance()
        {
            // Arrange
            DisposableCommand transientInstanceToDispose = null;

            var container = new Container();

            var lifestyle = new LifetimeScopeLifestyle();

            container.RegisterInitializer <DisposableCommand>(command =>
            {
                lifestyle.RegisterForDisposal(container, command);
            });

            using (container.BeginLifetimeScope())
            {
                transientInstanceToDispose = container.GetInstance <DisposableCommand>();

                // Act
            }

            // Assert
            Assert.IsTrue(transientInstanceToDispose.HasBeenDisposed);
        }
        public void WhenScopeEnds_CalledOutOfTheContextOfALifetimeScope_ThrowsException()
        {
            // Arrange
            var lifestyle = new LifetimeScopeLifestyle();

            var container = new Container();

            container.RegisterLifetimeScope <ConcreteCommand>();

            try
            {
                // Act
                lifestyle.WhenScopeEnds(container, () => { });

                // Assert
                Assert.Fail("Exception expected.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.IsTrue(ex.Message.Contains(
                                  "This method can only be called within the context of an active Lifetime Scope."),
                              "Actual: " + ex.Message);
            }
        }