Пример #1
0
        public async Task ShouldInterceptCommandWithMultipleDependencies()
        {
            var container = new ServiceContainer();

            container.RegisterCommandHandlers();
            container.Register <IFoo, Foo>();
            container.Register <IBar, Bar>();

            bool invoked   = false;
            IFoo passedFoo = null;
            IBar passedBar = null;

            container.RegisterCommandInterceptor <SampleCommand, (IBar bar, IFoo foo)>(async(command, handler, dependencies, token) =>
            {
                passedFoo = dependencies.foo;
                passedBar = dependencies.bar;
                invoked   = true;
                await handler.HandleAsync(command, token);
            });

            var command = new SampleCommand();

            using (var scope = container.BeginScope())
            {
                await container.GetInstance <ICommandHandler <SampleCommand> >().HandleAsync(command);

                invoked.Should().BeTrue();
                command.WasHandled.Should().BeTrue();
                passedFoo.Should().BeOfType <Foo>();
                passedBar.Should().BeOfType <Bar>();
            }
        }
Пример #2
0
        public async Task ShouldInterceptQueryHandlerWithMultipleDependencies()
        {
            var container = new ServiceContainer();

            container.RegisterQueryHandlers();
            container.Register <IFoo, Foo>();
            container.Register <IBar, Bar>();
            bool invoked   = false;
            IFoo passedFoo = null;
            IBar passedBar = null;

            container.RegisterQueryInterceptor <SampleQuery, SampleQueryResult, (IFoo foo, IBar bar)>(async(query, handler, dependencies, token) =>
            {
                passedFoo = dependencies.foo;
                passedBar = dependencies.bar;
                invoked   = true;
                return(await handler.HandleAsync(query, token));
            }
                                                                                                      );

            var query = new SampleQuery();

            using (var scope = container.BeginScope())
            {
                await container.GetInstance <IQueryHandler <SampleQuery, SampleQueryResult> >().HandleAsync(query);

                invoked.Should().BeTrue();
                query.WasHandled.Should().BeTrue();
                passedFoo.Should().BeOfType <Foo>();
                passedBar.Should().BeOfType <Bar>();
            }
        }
Пример #3
0
        public async Task ShouldInterceptCommandHandlerWithDependency()
        {
            var container = new ServiceContainer();

            container.RegisterCommandHandlers();
            container.Register <IFoo, Foo>();
            bool invoked   = false;
            IFoo passedFoo = null;

            container.RegisterCommandInterceptor <SampleCommand, IFoo>(async(command, handler, foo, token) =>
            {
                invoked   = true;
                passedFoo = foo;
                await handler.HandleAsync(command, token);
            }
                                                                       );

            var command = new SampleCommand();

            using (var scope = container.BeginScope())
            {
                await container.GetInstance <ICommandHandler <SampleCommand> >().HandleAsync(command);

                invoked.Should().BeTrue();
                command.WasHandled.Should().BeTrue();
                passedFoo.Should().BeOfType <Foo>();
            }
        }
Пример #4
0
        public async Task ShouldInterceptQueryHandler()
        {
            var container = new ServiceContainer();

            container.RegisterQueryHandlers();
            container.Register <IFoo, Foo>();
            bool invoked = false;

            container.RegisterQueryInterceptor <SampleQuery, SampleQueryResult>(async(query, handler, token) =>
            {
                invoked = true;
                return(await handler.HandleAsync(query, token));
            }
                                                                                );

            var query = new SampleQuery();

            using (var scope = container.BeginScope())
            {
                await container.GetInstance <IQueryHandler <SampleQuery, SampleQueryResult> >().HandleAsync(query);

                invoked.Should().BeTrue();
                query.WasHandled.Should().BeTrue();
            }
        }
Пример #5
0
        public static TForm CreateForm <TForm>() where TForm : Form
        {
            var scope = ServiceContainer.BeginScope();
            var form  = ServiceContainer.GetInstance <TForm>();

            form.Disposed += (sender, e) => { scope.Dispose(); };
            return(form);
        }
        public PerLogicalCallContextTests()
        {
            container = new ServiceContainer();
            container.Register<IFoo, Foo>(new PerScopeLifetime());
            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();

            scope = container.BeginScope();
        }
Пример #7
0
        public PerLogicalCallContextTests()
        {
            container = new ServiceContainer();
            container.Register <IFoo, Foo>(new PerScopeLifetime());
            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();

            scope = container.BeginScope();
        }
Пример #8
0
        public void ShouldCallDisposeOnlyOnceForSameInstance()
        {
            var servicecontainer = new ServiceContainer();

            using (servicecontainer.BeginScope())
            {
                servicecontainer.Register(sf => new TransientServiceWithInterface(), new PerRequestLifeTime());
                servicecontainer.Register <ISomeService>(sf => sf.GetInstance <TransientServiceWithInterface>(), new PerRequestLifeTime());

                using (servicecontainer.BeginScope())
                {
                    servicecontainer.GetInstance <ISomeService>();
                }

                Assert.Equal(1, TransientServiceWithInterface.instanceCounter);  // 1
                Assert.Equal(1, TransientServiceWithInterface.disposalCounters); // 2 !
            }
        }
        public void BeforeEachTest()
        {
            container.StartMocking <IUnitOfWork>(() => Mock.Of <IUnitOfWork>());
            container.StartMocking <IListItemRepository>(() => Mock.Of <IListItemRepository>());
            container.StartMocking <ICrudRepository <ShoppingList> >(() => Mock.Of <ICrudRepository <ShoppingList> >());
            container.StartMocking <IUserRepository>(() => Mock.Of <IUserRepository>());
            container.StartMocking <ICrudRepository <Permission> >(() => Mock.Of <ICrudRepository <Permission> >());

            scope = container.BeginScope();
        }
Пример #10
0
        static void Main(string[] args)
        {
            var container = new ServiceContainer();

            ContainerManager.Bootstrap(container);
            using (var scope = container.BeginScope())
            {
                var unitOfWork = container.GetInstance <IUnitOfWork>();
            }
        }
        public void EndCurrentScope_InScope_EndsScope()
        {
            var           container = new ServiceContainer();
            IScopeManager manager   = container.ScopeManagerProvider.GetScopeManager(container);

            container.BeginScope();
            container.ScopeManagerProvider.GetScopeManager(container).CurrentScope.Dispose();

            Assert.Null(manager.CurrentScope);
        }
Пример #12
0
        public void GetInstance_Continuation_ThrowException()
        {
            var container = new ServiceContainer();
            container.Register<IBar, Bar>(new PerScopeLifetime());
            container.Register<IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var instance = container.GetInstance<IAsyncFoo>();
                Assert.Throws<AggregateException>(() => instance.GetBar().Wait());                
            }
        }
Пример #13
0
        private static ServiceContainer CreateContainer()
        {
            var container = new ServiceContainer();

            container.Register <ITestProperty, TestProperty>();
            container.Register <ITestClass, TestClass>();
            container.Register <ITestFactory, TestFactory>();
            //container.RegisterInstance(container);
            container.Register <IWrapperFactory, WrapperFactory>();
            container.RegisterInstance <IServiceFactory>(container.BeginScope());
            //container.Register<IServiceFactory, IWrapperFactory>();
            return(container);
        }
Пример #14
0
        public void GetInstance_Continuation_ThrowException()
        {
            var container = new ServiceContainer();

            container.Register <IBar, Bar>(new PerScopeLifetime());
            container.Register <IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var instance = container.GetInstance <IAsyncFoo>();
                Assert.Throws <AggregateException>(() => instance.GetBar().Wait());
            }
        }
Пример #15
0
        public void GetInstance_Continuation_ReturnsInstance()
        {
            var container = new ServiceContainer();
            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();
            container.Register<IBar, Bar>(new PerScopeLifetime());
            container.Register<IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var instance = container.GetInstance<IAsyncFoo>();
                var bar = instance.GetBar().Result;
                Assert.IsAssignableFrom(typeof(IBar), bar);
            }
        }
Пример #16
0
        public void Scoped_Passing()
        {
            var container = new ServiceContainer();

            container.RegisterScoped <IOrderService, OrderServiceWithDependencyInjection>();
            container.RegisterScoped <IOrderNotifier, EMailOrderNotifier>();

            using (var scope = container.BeginScope())
            {
                var firstOrderService  = scope.GetInstance <IOrderService>();
                var secondOrderService = scope.GetInstance <IOrderService>();
                firstOrderService.Should().BeSameAs(secondOrderService);
            }
        }
        public async Task ShouldExecuteOpenGenericCommandHandler()
        {
            var container = new ServiceContainer();

            container.RegisterCommandHandlers();
            using (var scope = container.BeginScope())
            {
                var commandExecutor = scope.GetInstance <ICommandExecutor>();
                var command         = new DerivedCommand();
                await commandExecutor.ExecuteAsync(command);

                command.WasHandled.Should().BeTrue();
            }
        }
        public async Task ShouldExecuteQueryHandler()
        {
            var container = new ServiceContainer();

            container.RegisterQueryHandlers();
            using (var scope = container.BeginScope())
            {
                var queryExecutor = scope.GetInstance <IQueryExecutor>();
                var query         = new SampleQuery();
                var result        = await queryExecutor.ExecuteAsync(query);

                query.WasHandled.Should().BeTrue();
            }
        }
Пример #19
0
        public void RegisterPerThread_DifferentThreads_Success()
        {
            ITestCase testCase = new PerThreadTestCaseC(new LightInjectRegistration(), new LightInjectResolving());

            var c = new ServiceContainer();

            c = (ServiceContainer)testCase.Register(c, RegistrationKind.PerThread);
            ITestC obj1 = null;
            ITestC obj2 = null;


            var thread1 = new Thread(() =>
            {
                using (c.BeginScope())
                {
                    obj1 = c.GetInstance <ITestC>();
                }
            });
            var thread2 = new Thread(() =>
            {
                using (c.BeginScope())
                {
                    obj2 = c.GetInstance <ITestC>();
                }
            });

            thread1.Start();
            thread1.Join();
            thread2.Start();
            thread2.Join();


            CheckHelper.Check(obj1, true, true);
            CheckHelper.Check(obj2, true, true);
            CheckHelper.Check(obj1, obj2, false, false);
        }
Пример #20
0
        public void GetInstance_Continuation_ReturnsInstance()
        {
            var container = new ServiceContainer();

            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();
            container.Register <IBar, Bar>(new PerScopeLifetime());
            container.Register <IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var instance = container.GetInstance <IAsyncFoo>();
                var bar      = instance.GetBar().Result;
                Assert.IsAssignableFrom <IBar>(bar);
            }
        }
 public LightInjectObjectBuilder()
 {
     container = new ServiceContainer(new ContainerOptions
     {
         EnableVariance = false
     })
     {
         // Logical call context is necessary because the CurrentScope would be managed in a thread local
         // by default, if not specified otherwise, which leads to inproper scope
         // usage when executed with async code.
         ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider()
     };
     scope       = container.BeginScope();
     isRootScope = true;
 }
        public void PerRequestLifetime()
        {
            var container = new ServiceContainer();

            container.Register <A>()
            .Register <B>()
            .Register <C>(new PerRequestLifeTime());

            using (container.BeginScope())
            {
                var instanceOfA = container.GetInstance <A>();

                instanceOfA.InstanceOfC.MustNotBeSameAs(instanceOfA.InstanceOfB.InstanceOfC);
            }
        }
Пример #23
0
        public void GetInstance_SameExecutionContext_InstancesAreSame()
        {
            var container = new ServiceContainer();
            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();
            container.Register<IBar, Bar>(new PerScopeLifetime());
            container.Register<IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var firstBar = container.GetInstance<IBar>();
                var instance = container.GetInstance<IAsyncFoo>();
                var secondBar = instance.GetBar().Result;
                Assert.Same(firstBar, secondBar);
            }
        }
Пример #24
0
 public static void Main(string[] args)
 {
     FluentCommandLineParser<Arguments> parser = ParserBuilder.Build();
     var parserResult = parser.Parse(args);
     if (!parserResult.HasErrors && !parserResult.EmptyArgs)
     {
         Arguments argument = parser.Object;
         var container = new ServiceContainer();
         container.RegisterFrom<CompositionRoot>();
         using (var scope = container.BeginScope())
         {
             IFileParserManager fileParserManager = container.GetInstance<IFileParserManager>();
             FileParserResult parseResult = fileParserManager.ParseFileAsync(argument.Path).Result;
         }
     }
 }
        public void Init_ScopesWithDisposableService_DontThrowError()
        {
            ServiceContainer container = new ServiceContainer();

            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();

            // Register disposable Foo.
            container.Register <IFoo>(factory => new DisposableFoo(), new PerRequestLifeTime());

            using (var scope = container.BeginScope())
            {
                Enumerable.Range(0, 100)
                .AsParallel()
                .ForAll(num => scope.GetInstance <IFoo>());
            }
        }
Пример #26
0
        public async Task ShouldExecuteOpenGenericQueryHandler()
        {
            var container = new ServiceContainer();

            container.RegisterQueryHandlers();
            container.Register <IFoo, Foo>();
            using (var scope = container.BeginScope())
            {
                var queryExecutor = scope.GetInstance <IQueryExecutor>();
                var handler       = container.GetInstance <IQueryHandler <OpenGenericQuery <Derived>, Derived> >();
                var query         = new OpenGenericQuery <Derived>();
                var result        = await queryExecutor.ExecuteAsync(query);

                query.WasHandled.Should().BeTrue();
            }
        }
Пример #27
0
        public void GetInstance_SameExecutionContext_InstancesAreSame()
        {
            var container = new ServiceContainer();

            container.ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider();
            container.Register <IBar, Bar>(new PerScopeLifetime());
            container.Register <IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var firstBar  = container.GetInstance <IBar>();
                var instance  = container.GetInstance <IAsyncFoo>();
                var secondBar = instance.GetBar().Result;
                Assert.Same(firstBar, secondBar);
            }
        }
Пример #28
0
        private static async Task <IActor> CreateSectorAsync()
        {
            if (_sectorServiceContainer != null && !_sectorServiceContainer.IsDisposed)
            {
                DropActorEventSubscriptions();

                _sectorServiceContainer.Dispose();
            }

            _sectorServiceContainer = _globalServiceContainer.BeginScope();

            _startUp.ConfigureAux(_sectorServiceContainer);

            var schemeService        = _globalServiceContainer.GetInstance <ISchemeService>();
            var humanPlayer          = _globalServiceContainer.GetInstance <HumanPlayer>();
            var survivalRandomSource = _globalServiceContainer.GetInstance <ISurvivalRandomSource>();
            var propFactory          = _globalServiceContainer.GetInstance <IPropFactory>();
            var scoreManager         = _globalServiceContainer.GetInstance <IScoreManager>();

            var gameLoop               = _sectorServiceContainer.GetInstance <IGameLoop>();
            var sectorManager          = _sectorServiceContainer.GetInstance <ISectorManager>();
            var botActorTaskSource     = _sectorServiceContainer.GetInstance <ISectorActorTaskSource>("bot");
            var actorManager           = _sectorServiceContainer.GetInstance <IActorManager>();
            var monsterActorTaskSource = _sectorServiceContainer.GetInstance <IActorTaskSource>("monster");

            await sectorManager.CreateSectorAsync();

            sectorManager.CurrentSector.ScoreManager    = scoreManager;
            sectorManager.CurrentSector.HumanGroupExit += CurrentSector_HumanGroupExit;

            gameLoop.ActorTaskSources = new[] {
                botActorTaskSource,
                monsterActorTaskSource
            };

            var humanActor = CreateHumanActor(humanPlayer,
                                              schemeService,
                                              survivalRandomSource,
                                              propFactory,
                                              sectorManager,
                                              actorManager);

            CreateActorEventSubscriptions();

            return(humanActor);
        }
Пример #29
0
        public static void Main(string[] args)
        {
            FluentCommandLineParser <Arguments> parser = ParserBuilder.Build();
            var parserResult = parser.Parse(args);

            if (!parserResult.HasErrors && !parserResult.EmptyArgs)
            {
                Arguments argument  = parser.Object;
                var       container = new ServiceContainer();
                container.RegisterFrom <CompositionRoot>();
                using (var scope = container.BeginScope())
                {
                    IFileParserManager fileParserManager = container.GetInstance <IFileParserManager>();
                    FileParserResult   parseResult       = fileParserManager.ParseFileAsync(argument.Path).Result;
                }
            }
        }
Пример #30
0
        public void GetInstance_Continuation_ThrowException()
        {
            var container = new ServiceContainer();

            container.ScopeManagerProvider = new PerThreadScopeManagerProvider();
            container.Register <IBar, Bar>(new PerScopeLifetime());
            container.Register <IAsyncFoo, AsyncFoo>();

            using (container.BeginScope())
            {
                var instance = container.GetInstance <IAsyncFoo>();
                // This no longer throws since we injected lazy is closed around the scope.
                // Assert.Throws<AggregateException>(() => instance.GetBar().Wait());
                var bar = instance.GetBar().Result;
                Assert.NotNull(bar);
            }
        }
Пример #31
0
        public static IIocAppConfiguration UseLightInject(this IAppConfiguration configuration)
        {
            Ensure.NotNull(configuration, nameof(configuration));
            var contaier = new ServiceContainer {
                ScopeManagerProvider = new PerLogicalCallContextScopeManagerProvider()
            };
            var register = new IocRegistrar(contaier);
            var resolver = new IocResolver(new Lazy <Scope>(() => contaier.BeginScope()));

            register.RegisterInstance <IIocRegistrar>(register);
            register.RegisterInstance <IIocResolver>(resolver);
            //register.Register<IIocResolverScopeFactory,IocResolverScopeFactory>();
            contaier.Register <IIocResolverScopeFactory>(factory => new IocResolverScopeFactory(factory), new PerScopeLifetime());
            return(new IocAppConfiguration(configuration.ConfigDictionary)
            {
                Registrar = register,
                Resolver = resolver
            });
        }
Пример #32
0
        static void Main()
        {
            // Composition Root
            // We're using a DI container now
            var serviceContainer = new ServiceContainer();
            serviceContainer.Register<IReader, ConsoleReader>();
            serviceContainer.Register<IWriter>(f => new FileWriter(FilePath), "FileWriter", new PerRequestLifeTime());
            serviceContainer.Register<IWriter, ConsoleWriter>("ConsoleWriter");
            serviceContainer.Register<IWriter, CompositeWriter>();
            serviceContainer.Register<CopyProcess>();

            // Run the actual program
            // Obtain the root object of the object graph that is necessary to run this program
            using (serviceContainer.BeginScope())
            {
                var copyProcess = serviceContainer.GetInstance<CopyProcess>();
                copyProcess.Execute();
            } // Teardown happens here
        }
Пример #33
0
        public Initialization(IMod mod)
        {
            var container = new ServiceContainer();

            container.RegisterAssembly(GetType().Assembly);
            container.RegisterInstance(mod.Helper);
            container.RegisterInstance(mod.Monitor);
            container.Register <IHarmonyWrapper, HarmonyWrapper>();
            container.Register <IWrapperFactory, WrapperFactory>();
            container.Decorate <IMonitor, Logger>();
            container.RegisterInstance <IServiceFactory>(container.BeginScope());

            foreach (var service in container.AvailableServices)
            {
                mod.Monitor.Log(service.ServiceType.FullName + " | " + container.CanGetInstance(service.ServiceType, String.Empty), LogLevel.Debug);
            }

            container.GetInstance <IHarmonyPatch>();
            container.GetInstance <IDialogueApi>();
        }
Пример #34
0
        public static void Main()
        {
            // Composition Root
            // Register
            var container = new ServiceContainer();

            container.Register <IReader, ConsoleReader>()
            //.Register<IWriter, ConsoleWriter>()
            .Register <IWriter>(f => new FileWriter("text.txt"), new PerRequestLifeTime())
            .Register <CopyProcess>();

            // Resolve
            using (container.BeginScope())
            {
                var copyProcess = container.GetInstance <CopyProcess>();
                copyProcess.Copy();

                // Release
            }
        }
Пример #35
0
        public void Test()
        {
            var notFound = _container.CanGetInstance(typeof(DependencyStubSimple), string.Empty);

            Assert.IsFalse(notFound);

            _dependencyRegister.RegisterAssemblyDependencies(_container, new List <Assembly> {
                GetType().Assembly
            });

            var found = _container.CanGetInstance(typeof(DependencyStubSimple), string.Empty);

            Assert.IsTrue(found);

            using (_container.BeginScope())
            {
                var stub = _container.GetInstance <DependencyStubSimple>();
                Assert.IsNotNull(stub);
                Assert.IsInstanceOfType(stub, typeof(DependencyStubSimple));
            }
        }
        public void Dispose_OnAnotherThread_ShouldDisposeScope()
        {
            var           container      = new ServiceContainer();
            var           scope          = container.BeginScope();
            WeakReference scopeReference = new WeakReference(scope);

            // Dispose the scope on a different thread
            Thread disposeThread = new Thread(scope.Dispose);

            disposeThread.Start();
            disposeThread.Join();

            // We are now back on the starting thread and
            // although the scope was ended on another thread
            // the current scope on this thread should reflect that.
            var currentScope = container.ScopeManagerProvider.GetScopeManager(container).CurrentScope;

            Assert.Null(currentScope);
            scope = null;
            GC.Collect();
            Assert.False(scopeReference.IsAlive);
        }
 public LightInjecterScope(ServiceContainer container)
 {
     _container = container;
     
     _container.BeginScope();
 }
Пример #38
0
        public void EndCurrentScope_InScope_EndsScope()
        {
            var container = new ServiceContainer();
            ScopeManager manager = container.ScopeManagerProvider.GetScopeManager();
            
            container.BeginScope();
            container.EndCurrentScope();

            Assert.Null(manager.CurrentScope);
        }