Exemple #1
0
        public async Task Db_SalesService_Concurrency_AskClient()
        {
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                SalesService service = container.GetInstance <SalesService>();
                service.SetPolicy(DataConflictPolicy.AskClient);

                var article = await service.GetByIdAsync <Article>(this.dataSet.ArticlesIds.ElementAt(3));

                article.Title = "User1 Title 4";

                this.articlesSqlHelper.ModifyTitle(article.Id, "User2 Title 4");

                DataConflictException dce = Assert.ThrowsAsync <DataConflictException>(async() =>
                {
                    await service.ModifyAsync(article);
                });
                Assert.AreEqual(DalErrorType.BaseServiceDataConflictWithAskClientPolicy, dce.errorType);

                Assert.IsInstanceOf(typeof(Article), dce.CurrentValues);
                Assert.IsInstanceOf(typeof(Article), dce.DatabaseValues);

                Article currentValues  = (Article)dce.CurrentValues;
                Article databaseValues = (Article)dce.DatabaseValues;

                Assert.AreEqual(article.Id, databaseValues.Id);
                Assert.AreEqual("User2 Title 4", databaseValues.Title);

                Assert.AreEqual(article.Id, currentValues.Id);
                Assert.AreEqual("User1 Title 4", currentValues.Title);
            }
        }
    public void Cannot_correctly_resolve_scoped_services_as_singleton()
    {
        using var container = new Container();
        container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();
        container.AddAutoMapper(
            cfg =>
        {
            cfg.WithMapperAssemblyMarkerTypes(typeof(Source));
            cfg.AsSingleton();
        });

        container.Register <ISomeService, MutableService>(Lifestyle.Scoped);

        using (ThreadScopedLifestyle.BeginScope(container))
        {
            var mutableService = (MutableService)container.GetInstance <ISomeService>();
            mutableService.Value = 10;

            var mapper = container.GetInstance <IMapper>();

            var dest = mapper.Map <Dest2>(new Source2 {
                ConvertedValue = 5
            });

            dest.ConvertedValue.Should().Be(15);
        }
    }
        public void DisposingScope_ResolvingAnOpenGenericType_DisposesThatInstance()
        {
            // Arrange
            DisposableValidator <object> instanceToDispose;

            var container = new Container();

            // Call to EnableTransientDisposal is needed in case open-generic.
            DisposableTransientLifestyle.EnableForContainer(container);

            var lifestyle = new DisposableTransientLifestyle(new ThreadScopedLifestyle());

            // NOTE: Open-generic types are special, because they are resolved through unregistered type
            // resolution. This test will fail if the DisposableTransientLifestyle registers the initializer
            // lazily.
            container.Register(typeof(IValidator <>), typeof(DisposableValidator <>), lifestyle);

            var scope = ThreadScopedLifestyle.BeginScope(container);

            instanceToDispose = (DisposableValidator <object>)container.GetInstance <IValidator <object> >();

            // Act
            scope.Dispose();

            // Assert
            Assert.IsTrue(instanceToDispose.Disposed);
        }
        public void DisposingScope_WithMultipleDisposableTransientCreatedWithinScope_DisposesThoseInstances()
        {
            // Arrange
            DisposableUserRepository instanceToDispose1;
            DisposableUserRepository instanceToDispose2;

            var container = new Container();

            var lifestyle = new DisposableTransientLifestyle(new ThreadScopedLifestyle());

            container.Register <IUserRepository, DisposableUserRepository>(lifestyle);

            var scope = ThreadScopedLifestyle.BeginScope(container);

            instanceToDispose1 = (DisposableUserRepository)container.GetInstance <IUserRepository>();
            instanceToDispose2 = (DisposableUserRepository)container.GetInstance <IUserRepository>();

            // Act
            scope.Dispose();

            // Assert
            Assert.AreNotSame(instanceToDispose1, instanceToDispose2);
            Assert.IsTrue(instanceToDispose1.Disposed);
            Assert.IsTrue(instanceToDispose2.Disposed);
        }
Exemple #5
0
        /// <summary>
        /// The main entry point for the service.
        /// </summary>
        private static void Main()
        {
            try
            {
                // Explicitly set App.config file location to prevent confusion
                // ReSharper disable once AssignNullToNotNullAttribute
                Environment.CurrentDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "OJS.Workers.LocalWorker.exe.config");

                var container = new Container();
                Bootstrap.Start(container);

                using (ThreadScopedLifestyle.BeginScope(container))
                {
                    var localWorkerService = container.GetInstance <LocalWorkerService>();

                    ServiceBase.Run(localWorkerService);
                }
            }
            catch (Exception exception)
            {
                const string Source = "OJS.Workers.LocalWorker";
                if (!EventLog.SourceExists(Source))
                {
                    EventLog.CreateEventSource(Source, "Application");
                }

                EventLog.WriteEntry(Source, exception.ToString(), EventLogEntryType.Error);
            }
        }
Exemple #6
0
    public void CanUseDefaultInjectedIMapperInSingletonService()
    {
        // Arrange
        using var container = new Container();
        container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();
        container.Register <ISomeService>(() => new FooService(5), Lifestyle.Transient);
        container.Register <ISingletonService, TestSingletonService>(Lifestyle.Singleton);
        container.AddAutoMapper(
            cfg =>
        {
            cfg.WithMapperAssemblyMarkerTypes(typeof(ServiceLifetimeTests));
            cfg.WithMapperConfigurationExpressionAction((_, expression) => expression.CreateMap <Foo, Bar>().ReverseMap());
        });
        Bar actual;

        // Act
        using (ThreadScopedLifestyle.BeginScope(container))
        {
            var service = container.GetInstance <ISingletonService>();
            actual = service.DoTheThing(new Foo {
                TheValue = 1
            });
        }

        // Assert
        actual.Should().NotBeNull();
        actual.TheValue.Should().Be(1);
    }
 public void DBDestroy()
 {
     using (ThreadScopedLifestyle.BeginScope(container))
     {
         this.Database.Database.EnsureDeleted();
     }
 }
Exemple #8
0
        public void Db_ErrorsReportingService_LogExceptionAsync_WithInner()
        {
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                ErrorsReportingService service = container.GetInstance <ErrorsReportingService>();

                try
                {
                    ExceptionGenerator.ThrowsTwo();
                }
                catch (Exception exception)
                {
                    int?id = null;
                    Assert.That(async() =>
                    {
                        id = await service.LogExceptionAsync(this.dataSet.ApplicationsIds.ElementAt(0), exception, "ErrorType.Specific");
                    }, Throws.Nothing);

                    Assert.IsNotNull(id);

                    ErrorReportException ex      = this.exceptionsSqlHelper.GetBy(id.Value);
                    ErrorReportException innerEx = this.exceptionsSqlHelper.GetBy(ex.IdInnerException.Value);

                    Assert.AreEqual("Two", ex.Message);
                    Assert.AreEqual("One", innerEx.Message);
                }
            }
        }
        private static void BenchSimpleInjector()
        {
            var services = new ServiceCollection();

            services.AddScoped <IValueProvider, ValueProvider>();
            services.AddLogging();

            var container = new SimpleInjector.Container();

            services.AddSimpleInjector(container);

            services.BuildServiceProvider().UseSimpleInjector(container);

            Launch("SimpleInjector (ThreadScoped)", (i) =>
            {
                using (var serviceScope = ThreadScopedLifestyle.BeginScope(container))
                {
                    var valueProvider = serviceScope.GetRequiredService <IValueProvider>();
                    valueProvider.GetValue(i);
                }
            });

            Launch("SimpleInjector (AsyncScopedLifestyle)", (i) =>
            {
                using (var serviceScope = AsyncScopedLifestyle.BeginScope(container))
                {
                    var valueProvider = serviceScope.GetRequiredService <IValueProvider>();
                    valueProvider.GetValue(i);
                }
            });
        }
        public void GetInstance_ResolveMultipleLifetimeScopedServicesWithStrangeEqualsImplementations_CorrectlyDisposesAllInstances()
        {
            // Arrange
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();

            container.Register <DisposableCommandWithOverriddenEquality1>(Lifestyle.Scoped);
            container.Register <DisposableCommandWithOverriddenEquality2>(Lifestyle.Scoped);

            // Act
            DisposableCommandWithOverriddenEquality1 command1;
            DisposableCommandWithOverriddenEquality2 command2;

            // Act
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                command1 = container.GetInstance <DisposableCommandWithOverriddenEquality1>();
                command2 = container.GetInstance <DisposableCommandWithOverriddenEquality2>();

                // Give both instances the same hash code. Both have an equals implementation that compared
                // using the hash code, which make them look like they're the same instance.
                command1.HashCode = 1;
                command2.HashCode = 1;
            }

            // Assert
            string assertMessage =
                "Dispose is expected to be called on this command, even when it contains a GetHashCode and " +
                "Equals implementation that is totally screwed up, since storing disposable objects, " +
                "should be completely independant to this implementation. ";

            Assert.AreEqual(1, command1.DisposeCount, assertMessage + "command1");
            Assert.AreEqual(1, command2.DisposeCount, assertMessage + "command2");
        }
        public void LifetimeScopeDispose_WithTransientRegisteredForDisposal_DisposesThatInstance()
        {
            // Arrange
            DisposableCommand transientInstanceToDispose = null;

            var container = new Container();

            container.Options.EnableAutoVerification = false;

            container.Register <DisposableCommand>();

            var lifestyle = new ThreadScopedLifestyle();

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

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

                // Act
            }

            // Assert
            Assert.IsTrue(transientInstanceToDispose.HasBeenDisposed);
        }
        public void GetCurrentLifetimeScope_DisposingTheMiddleScopeBeforeInnerScope_ReturnsOuterScope()
        {
            // Arrange
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();

            var instanceToDispose = new DisposableCommand();

            using (Scope outerScope = ThreadScopedLifestyle.BeginScope(container))
            {
                Scope middleScope = ThreadScopedLifestyle.BeginScope(container);

                Scope innerScope = ThreadScopedLifestyle.BeginScope(container);

                middleScope.Dispose();
                innerScope.Dispose();

                // Act
                Scope actualScope = Lifestyle.Scoped.GetCurrentScope(container);

                // Assert
                Assert.AreSame(outerScope, actualScope,
                               "Since the middle scope is already disposed, the current scope should be the outer.");
            }
        }
        public void CreateHybrid_WithFallbackLifestyleWithActiveScope_UsesDefaultScopedLifestyle()
        {
            // Arrange
            var hybrid = Lifestyle.CreateHybrid(
                defaultLifestyle: new ThreadScopedLifestyle(),
                fallbackLifestyle: Lifestyle.Singleton);

            var container = ContainerFactory.New();

            container.Register <IUserRepository, SqlUserRepository>(hybrid);

            IUserRepository provider1;
            IUserRepository provider2;

            // Act
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                provider1 = container.GetInstance <IUserRepository>();
            }

            using (ThreadScopedLifestyle.BeginScope(container))
            {
                provider2 = container.GetInstance <IUserRepository>();
            }

            // Assert
            Assert.AreNotSame(provider1, provider2);
        }
        public void GetCurrentLifetimeScope_DisposingAnInnerScope_ShouldNeverCauseToBeSetToInnerScope()
        {
            // Arrange
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();

            var instanceToDispose = new DisposableCommand();

            using (var outerScope = ThreadScopedLifestyle.BeginScope(container))
            {
                var outerMiddleScope = ThreadScopedLifestyle.BeginScope(container);

                var innerMiddleScope = ThreadScopedLifestyle.BeginScope(container);

                var innerScope = ThreadScopedLifestyle.BeginScope(container);

                // This will cause GetCurrentLifetimeScope to become outerScope.
                outerMiddleScope.Dispose();

                // This should not cause BeginLifetimeScope to change
                innerScope.Dispose();

                // Act
                Scope actualScope = Lifestyle.Scoped.GetCurrentScope(container);

                // Assert
                Assert.AreSame(outerScope, actualScope,
                               "Even though the inner middle scope never got disposed, the inner scope should not " +
                               "this scope upon disposal. The outer scope should retain focus.");
            }
        }
        public void LifetimeScopeDispose_WithInstanceExplicitlyRegisteredForDisposal_DisposesThatInstance()
        {
            // Arrange
            var container = new Container();

            var lifestyle = new ThreadScopedLifestyle();

            // Transient
            container.Register <ICommand, DisposableCommand>();

            container.RegisterInitializer <DisposableCommand>(instance =>
            {
                Scope scope = lifestyle.GetCurrentScope(container);

                // The following line explictly registers the transient DisposableCommand for disposal when
                // the lifetime scope ends.
                scope.RegisterForDisposal(instance);
            });

            DisposableCommand command;

            // Act
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                command = container.GetInstance <DisposableCommand>();
            }

            // Assert
            Assert.IsTrue(command.HasBeenDisposed,
                          "The transient instance was expected to be disposed, because it was registered for disposal.");
        }
        public void GetCurrentLifetimeScope_AfterMiddleScopeDisposedWhileInnerScopeNotDisposed_ReturnsOuterScope()
        {
            // Arrange
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();

            var instanceToDispose = new DisposableCommand();

            using (var outerScope = ThreadScopedLifestyle.BeginScope(container))
            {
                var middleScope = ThreadScopedLifestyle.BeginScope(container);

                var innerScope = ThreadScopedLifestyle.BeginScope(container);

                middleScope.Dispose();

                // Act
                Scope actualScope = Lifestyle.Scoped.GetCurrentScope(container);

                string scopeName =
                    object.ReferenceEquals(actualScope, null) ? "null" :
                    object.ReferenceEquals(actualScope, innerScope) ? "inner" :
                    object.ReferenceEquals(actualScope, middleScope) ? "middle" :
                    object.ReferenceEquals(actualScope, outerScope) ? "outer" :
                    "other";

                // Assert
                Assert.AreSame(outerScope, actualScope, "Expected: outer. Actual: " + scopeName + " scope.");
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.ColoredConsole()
                         .CreateLogger();

            Console.Title = "RPC  Client Test";
            while (true)
            {
                using (ThreadScopedLifestyle.BeginScope(container))
                {
                    try
                    {
                        IUserService userService = container.GetInstance <IUserService>();
                        var          result      = userService.SayHello(new User {
                            name = "Power Yang", age = 19
                        });
                        var users = userService.GetAllUsers();
                        Console.WriteLine(result);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                Console.ReadKey();
            }
        }
        public void ResolvingDisposableTransientInstance_WithEnableTransientDisposalCalledTwice_DisposesTheInstanceOnce()
        {
            // Arrange
            DisposableUserRepository instanceToDispose;

            var container = new Container();

            DisposableTransientLifestyle.EnableForContainer(container);
            DisposableTransientLifestyle.EnableForContainer(container);

            var lifestyle = new DisposableTransientLifestyle(new ThreadScopedLifestyle());

            container.Register <IUserRepository, DisposableUserRepository>(lifestyle);

            var scope = ThreadScopedLifestyle.BeginScope(container);

            instanceToDispose = (DisposableUserRepository)container.GetInstance <IUserRepository>();

            Assert.IsFalse(instanceToDispose.Disposed, "Test setup failed");

            // Act
            scope.Dispose();

            // Assert
            Assert.AreEqual(1, instanceToDispose.DisposeCount);
        }
Exemple #19
0
        /// <summary>
        /// Removed args as it is unused
        /// </summary>
        static void Main()
        {
            //Using a scoped lifestyle as this thread will only run once
            using (ThreadScopedLifestyle.BeginScope(Container))
            {
                // Using Service locator pattern since this is a console app
                var searchService = Container.GetInstance <ISearchService>();

                //Get list of words
                var words = searchService.GetWords();

                //Get the height and width of the grid
                var height = PromptForValue("height");
                var width  = PromptForValue("width");

                //Get the randomly generated grid
                var charGrid = searchService.GetCharGrid(height, width);

                //Using the character grid and list of words retrieved, perform word search and return words found as well as their location
                var result = searchService.SearchGridForWords(charGrid, words);

                //For every word found, print out the grid, and where it was found on the grid
                foreach (var keyValuePair in result)
                {
                    System.Console.WriteLine(keyValuePair.Key);
                    DisplayCharGrid(charGrid, keyValuePair.Value);
                }


                System.Console.ReadLine();
            }
        }
        public void CreateHybrid_TwoScopedLifestyles_ResolvesFromBothLifestyles()
        {
            // Arrange
            var scope = new Scope();

            var container = new Container();

            container.Options.DefaultScopedLifestyle = Lifestyle.CreateHybrid(
                defaultLifestyle: new ThreadScopedLifestyle(),
                fallbackLifestyle: new CustomScopedLifestyle(scope));

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

            // Act
            IUserRepository repo1 = container.GetInstance <IUserRepository>();
            IUserRepository repo2 = null;

            using (ThreadScopedLifestyle.BeginScope(container))
            {
                repo2 = container.GetInstance <IUserRepository>();
            }

            // Assert
            Assert.AreNotSame(repo1, repo2);
        }
        public void LifetimeScopeDispose_WithWhenScopeEndsRegistration_CallsTheRegisteredAction()
        {
            // Arrange
            int actionCallCount = 0;

            var container = new Container();

            var lifestyle = new ThreadScopedLifestyle();

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

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

            using (ThreadScopedLifestyle.BeginScope(container))
            {
                container.GetInstance <DisposableCommand>();

                // Act
            }

            // Assert
            Assert.AreEqual(1, actionCallCount, "Delegate is expected to be called exactly once.");
        }
 public TResult Handle(TQuery query)
 {
     using (ThreadScopedLifestyle.BeginScope(container))
     {
         var handler = this.handlerProvider();
         return(handler.Handle(query));
     }
 }
        public void BeginLifetimeScope_WithoutAnyLifetimeScopeRegistrationsAndWithoutExplicitlyEnablingLifetimeScoping_Succeeds()
        {
            // Arrange
            var container = new Container();

            // Act
            ThreadScopedLifestyle.BeginScope(container);
        }
Exemple #24
0
 public static async Task <List <Article> > GetArticlesAsync(int idCategory)
 {
     using (ThreadScopedLifestyle.BeginScope(IoCConfiguration.Container))
     {
         ISalesManager salesManager = IoCConfiguration.Container.GetInstance <ISalesManager>();
         return(await salesManager.GetArticlesAsync(idCategory));
     }
 }
 public void DBInit()
 {
     // Get the context from the container and ensure migrations
     using (ThreadScopedLifestyle.BeginScope(container))
     {
         this.Database.Migrate();
     }
 }
Exemple #26
0
 public void Save(List <Member> members)
 {
     using (ThreadScopedLifestyle.BeginScope(container))
     {
         IMemberService service = this.decorateeFactory.Invoke();
         service.Save(members);
     }
 }
Exemple #27
0
 public static async Task SaveAsync(Exception exception, AssemblyName assemblyName, string errorCode)
 {
     using (ThreadScopedLifestyle.BeginScope(IoCConfiguration.Container))
     {
         IErrorsReportingManager manager = IoCConfiguration.Container.GetInstance <IErrorsReportingManager>();
         await manager.LogErrorAsync(exception, assemblyName, errorCode);
     }
 }
Exemple #28
0
        public void ScenarioSetup()
        {
            _scope = ThreadScopedLifestyle.BeginScope(Container);

            AuthFixture?.ConfigureTestUser(Container, GetFeatureTenantId());

            BaseTestFixture.ScenarioSetup();
        }
        public void BeginLifetimeScope_WithNullArgument_ThrowsExpectedException()
        {
            // Act
            Action action = () => ThreadScopedLifestyle.BeginScope(null);

            // Assert
            AssertThat.Throws <ArgumentNullException>(action);
        }
Exemple #30
0
 public void Handle(TCommand command)
 {
     using (ThreadScopedLifestyle.BeginScope(container))
     {
         var handler = this.handlerProvider();
         handler.Handle(command);
     }
 }