public void AbstractClassConstrainedOpenGenericServicesCanBeResolved()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddTransient(typeof(IFakeOpenGenericService <>), typeof(FakeOpenGenericService <>));
            collection.AddTransient(typeof(IFakeOpenGenericService <>), typeof(ClassWithAbstractClassConstraint <>));
            var poco = new PocoClass();

            collection.AddSingleton(poco);
            var classInheritingClassInheritingAbstractClass = new ClassInheritingClassInheritingAbstractClass();

            collection.AddSingleton(classInheritingClassInheritingAbstractClass);
            var provider = CreateServiceProvider(collection);
            // Act
            var allServices         = provider.GetServices <IFakeOpenGenericService <ClassInheritingClassInheritingAbstractClass> >().ToList();
            var constrainedServices = provider.GetServices <IFakeOpenGenericService <PocoClass> >().ToList();

            // Assert
            Assert.Equal(2, allServices.Count);
            Assert.Same(classInheritingClassInheritingAbstractClass, allServices[0].Value);
            Assert.Same(classInheritingClassInheritingAbstractClass, allServices[1].Value);
            Assert.Equal(1, constrainedServices.Count);
            Assert.Same(poco, constrainedServices[0].Value);
        }
예제 #2
0
        public void RegistrationOrderIsPreservedWhenServicesAreIEnumerableResolved()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddTransient(typeof(IFakeMultipleService), typeof(FakeOneMultipleService));
            collection.AddTransient(typeof(IFakeMultipleService), typeof(FakeTwoMultipleService));

            var provider = CreateServiceProvider(collection);

            collection.Reverse();
            var providerReversed = CreateServiceProvider(collection);

            // Act
            var services         = provider.GetService <IEnumerable <IFakeMultipleService> >();
            var servicesReversed = providerReversed.GetService <IEnumerable <IFakeMultipleService> >();

            // Assert
            Assert.Collection(services,
                              service => Assert.IsType <FakeOneMultipleService>(service),
                              service => Assert.IsType <FakeTwoMultipleService>(service));

            Assert.Collection(servicesReversed,
                              service => Assert.IsType <FakeTwoMultipleService>(service),
                              service => Assert.IsType <FakeOneMultipleService>(service));
        }
예제 #3
0
        public void RegisterFromServices()
        {
            var serviceCollection = new TestServiceCollection();

            serviceCollection.Add(new ServiceDescriptor(
                                      typeof(TestData), _ => new TestData(), ServiceLifetime.Transient));
            serviceCollection.Add(new ServiceDescriptor(
                                      typeof(TestInjection), typeof(TestInjection), ServiceLifetime.Transient));
            serviceCollection.Add(new ServiceDescriptor(typeof(string), "abc"));
            serviceCollection.Add(new ServiceDescriptor(
                                      typeof(ITestGenericService <,>), typeof(TestGenericService <,>), ServiceLifetime.Transient));
            IContainer container = new Container();

            container.RegisterFromServiceCollection(serviceCollection);
            var provider  = container.AsServiceProvider();
            var injection = (TestInjection)provider.GetService(typeof(TestInjection));

            Assert.IsTrue(injection != null);
            Assert.IsTrue(injection.Data != null);
            var str = (string)provider.GetService(typeof(string));

            Assert.Equals(str, "abc");
            var list = provider.GetService(typeof(ITestGenericService <int, string>));

            Assert.Equals(list.GetType(), typeof(TestGenericService <int, string>));
        }
        public void GetServiceOrCreateInstanceUnregisteredService()
        {
            lock (CreationCountFakeService.InstanceLock)
            {
                // Arrange
                // Reset the count because test order is not guaranteed
                CreationCountFakeService.InstanceCount = 0;

                var serviceCollection = new TestServiceCollection()
                                        .AddTransient <IFakeService, FakeService>();
                var serviceProvider = CreateServiceProvider(serviceCollection);

                // Act and Assert
                var service = (CreationCountFakeService)ActivatorUtilities.GetServiceOrCreateInstance(
                    serviceProvider,
                    typeof(CreationCountFakeService));
                Assert.NotNull(service);
                Assert.Equal(1, service.InstanceId);
                Assert.Equal(1, CreationCountFakeService.InstanceCount);

                service = ActivatorUtilities.GetServiceOrCreateInstance <CreationCountFakeService>(serviceProvider);
                Assert.NotNull(service);
                Assert.Equal(2, service.InstanceId);
                Assert.Equal(2, CreationCountFakeService.InstanceCount);
            }
        }
예제 #5
0
        // Don't care
        //[Fact]
        public void DisposesInReverseOrderOfCreation()
        {
            // Arrange
            var serviceCollection = new TestServiceCollection();

            serviceCollection.AddSingleton <FakeDisposeCallback>();
            serviceCollection.AddTransient <IFakeOuterService, FakeDisposableCallbackOuterService>();
            serviceCollection.AddSingleton <IFakeMultipleService, FakeDisposableCallbackInnerService>();
            serviceCollection.AddScoped <IFakeMultipleService, FakeDisposableCallbackInnerService>();
            serviceCollection.AddTransient <IFakeMultipleService, FakeDisposableCallbackInnerService>();
            serviceCollection.AddSingleton <IFakeService, FakeDisposableCallbackInnerService>();
            var serviceProvider = CreateServiceProvider(serviceCollection);

            var callback         = serviceProvider.GetService <FakeDisposeCallback>();
            var outer            = serviceProvider.GetService <IFakeOuterService>();
            var multipleServices = outer.MultipleServices.ToArray();

            // Act
            ((IDisposable)serviceProvider).Dispose();

            // Assert
            Assert.Equal(outer, callback.Disposed[0]);
            Assert.Equal(multipleServices.Reverse(), callback.Disposed.Skip(1).Take(3).OfType <IFakeMultipleService>());
            Assert.Equal(outer.SingleService, callback.Disposed[4]);
        }
예제 #6
0
        public void ScopedServices_FromCachedScopeFactory_CanBeResolvedAndDisposed()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddScoped <IFakeScopedService, FakeService>();
            var provider           = CreateServiceProvider(collection);
            var cachedScopeFactory = provider.GetService <IServiceScopeFactory>();

            // Act
            for (var i = 0; i < 3; i++)
            {
                FakeService outerScopedService;
                using (var outerScope = cachedScopeFactory.CreateScope())
                {
                    FakeService innerScopedService;
                    using (var innerScope = outerScope.ServiceProvider.CreateScope())
                    {
                        outerScopedService = outerScope.ServiceProvider.GetService <IFakeScopedService>() as FakeService;
                        innerScopedService = innerScope.ServiceProvider.GetService <IFakeScopedService>() as FakeService;

                        // Assert
                        Assert.NotNull(outerScopedService);
                        Assert.NotNull(innerScopedService);
                        Assert.NotSame(outerScopedService, innerScopedService);
                    }

                    Assert.False(outerScopedService.Disposed);
                    Assert.True(innerScopedService.Disposed);
                }

                Assert.True(outerScopedService.Disposed);
            }
        }
예제 #7
0
        public void SingletonServicesComeFromRootProvider()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddSingleton <IFakeSingletonService, FakeService>();
            var         provider = CreateServiceProvider(collection);
            FakeService disposableService1;
            FakeService disposableService2;

            // Act and Assert
            using (var scope = provider.CreateScope())
            {
                var service = scope.ServiceProvider.GetService <IFakeSingletonService>();
                disposableService1 = Assert.IsType <FakeService>(service);
                Assert.False(disposableService1.Disposed);
            }

            Assert.False(disposableService1.Disposed);

            using (var scope = provider.CreateScope())
            {
                var service = scope.ServiceProvider.GetService <IFakeSingletonService>();
                disposableService2 = Assert.IsType <FakeService>(service);
                Assert.False(disposableService2.Disposed);
            }

            Assert.False(disposableService2.Disposed);
            Assert.Same(disposableService1, disposableService2);
        }
예제 #8
0
        //[InlineData(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>),typeof(IFakeOpenGenericService<IServiceProvider>), ServiceLifetime.Singleton)]
        public void ResolvesDifferentInstancesForServiceWhenResolvingEnumerable(Type serviceType, Type implementation,
                                                                                Type resolve, ServiceLifetime lifetime)
        {
            // Arrange
            var serviceCollection = new TestServiceCollection
            {
                ServiceDescriptor.Describe(serviceType, implementation, lifetime),
                ServiceDescriptor.Describe(serviceType, implementation, lifetime),
                ServiceDescriptor.Describe(serviceType, implementation, lifetime)
            };

            var serviceProvider = CreateServiceProvider(serviceCollection);

            using (var scope = serviceProvider.CreateScope())
            {
                var enumerable =
                    (scope.ServiceProvider.GetService(typeof(IEnumerable <>).MakeGenericType(resolve)) as IEnumerable)
                    .OfType <object>().ToArray();
                var service = scope.ServiceProvider.GetService(resolve);

                // Assert
                Assert.Equal(3, enumerable.Length);
                Assert.NotNull(enumerable[0]);
                Assert.NotNull(enumerable[1]);
                Assert.NotNull(enumerable[2]);

                Assert.NotEqual(enumerable[0], enumerable[1]);
                Assert.NotEqual(enumerable[1], enumerable[2]);
                Assert.Equal(service, enumerable[2]);
            }
        }
예제 #9
0
        public void ResolvesMixedOpenClosedGenericsAsEnumerable()
        {
            // Arrange
            var serviceCollection = new TestServiceCollection();
            var instance          = new FakeOpenGenericService <PocoClass>(null);

            serviceCollection.AddTransient <PocoClass, PocoClass>();
            serviceCollection.AddSingleton(typeof(IFakeOpenGenericService <PocoClass>), typeof(FakeService));
            serviceCollection.AddSingleton(typeof(IFakeOpenGenericService <>), typeof(FakeOpenGenericService <>));
            serviceCollection.AddSingleton <IFakeOpenGenericService <PocoClass> >(instance);

            var serviceProvider = CreateServiceProvider(serviceCollection);

            var enumerable = serviceProvider.GetService <IEnumerable <IFakeOpenGenericService <PocoClass> > >().ToArray();

            // Assert
            Assert.Equal(3, enumerable.Length);
            Assert.NotNull(enumerable[0]);
            Assert.NotNull(enumerable[1]);
            Assert.NotNull(enumerable[2]);

            Assert.Equal(instance, enumerable[2]);

            // Lamar is NOT making this assumption about ordering
            //Assert.IsType<FakeService>(enumerable[0]);
        }
        public void SingletonServiceCanBeResolvedFromScope()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddSingleton <ClassWithServiceProvider>();
            var provider = CreateServiceProvider(collection);

            // Act
            IServiceProvider         scopedSp1 = null;
            IServiceProvider         scopedSp2 = null;
            ClassWithServiceProvider instance1 = null;
            ClassWithServiceProvider instance2 = null;

            using (var scope1 = provider.CreateScope())
            {
                scopedSp1 = scope1.ServiceProvider;
                instance1 = scope1.ServiceProvider.GetRequiredService <ClassWithServiceProvider>();
            }

            using (var scope2 = provider.CreateScope())
            {
                scopedSp2 = scope2.ServiceProvider;
                instance2 = scope2.ServiceProvider.GetRequiredService <ClassWithServiceProvider>();
            }

            // Assert
            Assert.Same(instance1.ServiceProvider, instance2.ServiceProvider);
            Assert.NotSame(instance1.ServiceProvider, scopedSp1);
            Assert.NotSame(instance2.ServiceProvider, scopedSp2);
        }
예제 #11
0
        public void FactoryServicesCanBeCreatedByGetService()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddTransient <IFakeService, FakeService>();
            collection.AddTransient <IFactoryService>(p =>
            {
                var fakeService = p.GetRequiredService <IFakeService>();
                return(new TransientFactoryService
                {
                    FakeService = fakeService,
                    Value = 42
                });
            });
            var provider = CreateServiceProvider(collection);

            // Act
            var service = provider.GetService <IFactoryService>();

            // Assert
            Assert.NotNull(service);
            Assert.Equal(42, service.Value);
            Assert.NotNull(service.FakeService);
            Assert.IsType <FakeService>(service.FakeService);
        }
예제 #12
0
        public void NoOptions_OnlyDefaultServicesRegistered()
        {
            var fakeCollection = new TestServiceCollection();

            fakeCollection.AddSeaOrDewHandlers();

            ServicesAssert.OnlyHandlerResolversRegistered(fakeCollection);
        }
예제 #13
0
        public void NullLambda_CorrectlyAddsMainServices()
        {
            var fakeCollection = new TestServiceCollection();

            fakeCollection.AddSeaOrDewHandlers((Action <SeaOrDewOptions>)null);

            ServicesAssert.OnlyHandlerResolversRegistered(fakeCollection);
        }
예제 #14
0
        public void PassOptions_CorrectlyAddsMainServices()
        {
            var fakeCollection = new TestServiceCollection();

            fakeCollection.AddSeaOrDewHandlers(new SeaOrDewOptions());

            ServicesAssert.OnlyHandlerResolversRegistered(fakeCollection);
        }
예제 #15
0
        public void CanCreateEmptyEnumerableDependency()
        {
            var serviceCollection = new TestServiceCollection();

            serviceCollection.AddTransient <ServiceWithEnumerableDependency <IFoo> >();
            var serviceProvider = CreateServiceProvider(serviceCollection);
            var service         = serviceProvider.GetService <ServiceWithEnumerableDependency <IFoo> >();

            Assert.Empty(service.Dependencies);
        }
예제 #16
0
        public void OptionsLambda_CorrectlyAddsMainServices()
        {
            var fakeCollection = new TestServiceCollection();

            fakeCollection.AddSeaOrDewHandlers(options =>
            {
            });

            ServicesAssert.OnlyHandlerResolversRegistered(fakeCollection);
        }
        public void TypeActivatorEnablesYouToCreateAnyTypeWithServicesEvenWhenNotInIocContainer(CreateInstanceFunc createFunc)
        {
            // Arrange
            var serviceCollection = new TestServiceCollection()
                                    .AddTransient <IFakeService, FakeService>();
            var serviceProvider = CreateServiceProvider(serviceCollection);

            var anotherClass = CreateInstance <AnotherClass>(createFunc, serviceProvider);

            Assert.NotNull(anotherClass.FakeService);
        }
예제 #18
0
        public void QueryRegistersCorrectly()
        {
            var fakeCollection = new TestServiceCollection();
            fakeCollection.RegisterQueryHandler<TestQueryHandler>();

            Assert.Collection(fakeCollection,
                s =>
                {
                    Assert.Equal(typeof(IQueryHandler<TestQuery, TestQueryResult>), s.ServiceType);
                    Assert.Equal(typeof(TestQueryHandler), s.ImplementationType);
                });
        }
        public void AttemptingToResolveNonexistentServiceReturnsNull()
        {
            // Arrange
            var collection = new TestServiceCollection();
            var provider   = CreateServiceProvider(collection);

            // Act
            var service = provider.GetService <INonexistentService>();

            // Assert
            Assert.Null(service);
        }
        public void NonexistentServiceCanBeIEnumerableResolved()
        {
            // Arrange
            var collection = new TestServiceCollection();
            var provider   = CreateServiceProvider(collection);

            // Act
            var services = provider.GetService <IEnumerable <INonexistentService> >();

            // Assert
            Assert.Empty(services);
        }
        public void ServiceProviderRegistersServiceScopeFactory()
        {
            // Arrange
            var collection = new TestServiceCollection();
            var provider   = CreateServiceProvider(collection);

            // Act
            var scopeFactory = provider.GetService <IServiceScopeFactory>();

            // Assert
            Assert.NotNull(scopeFactory);
        }
        public void TypeActivatorWorksWithCtorWithOptionalArgs_WithStructDefaults(CreateInstanceFunc createFunc)
        {
            // Arrange
            var provider        = new TestServiceCollection();
            var serviceProvider = CreateServiceProvider(provider);

            // Act
            var anotherClass = CreateInstance <ClassWithOptionalArgsCtorWithStructs>(createFunc, serviceProvider);

            // Assert
            Assert.NotNull(anotherClass);
        }
예제 #23
0
        public void CommandRegistersCorrectly()
        {
            var fakeCollection = new TestServiceCollection();

            fakeCollection.RegisterCommandHandler <CustomTestCommandHandler>();

            Assert.Collection(fakeCollection,
                              s =>
            {
                Assert.Equal(typeof(ICustomCommandHandler <CustomTestCommand, CustomTestCommandResult>), s.ServiceType);
                Assert.Equal(typeof(CustomTestCommandHandler), s.ImplementationType);
            });
        }
        public void SelfResolveThenDispose()
        {
            // Arrange
            var collection = new TestServiceCollection();
            var provider   = CreateServiceProvider(collection);

            // Act
            var serviceProvider = provider.GetService <IServiceProvider>();

            // Assert
            Assert.NotNull(serviceProvider);
            (provider as IDisposable)?.Dispose();
        }
        public void TypeActivatorWorksWithCtorWithOptionalArgs(CreateInstanceFunc createFunc)
        {
            // Arrange
            var provider        = new TestServiceCollection();
            var serviceProvider = CreateServiceProvider(provider);

            // Act
            var anotherClass = CreateInstance <ClassWithOptionalArgsCtor>(createFunc, serviceProvider);

            // Assert
            Assert.NotNull(anotherClass);
            Assert.Equal("BLARGH", anotherClass.Whatever);
        }
        public void UnRegisteredServiceAsConstructorParameterThrowsException(CreateInstanceFunc createFunc)
        {
            var serviceCollection = new TestServiceCollection()
                                    .AddSingleton <CreationCountFakeService>();
            var serviceProvider = CreateServiceProvider(serviceCollection);

            var ex = Assert.Throws <InvalidOperationException>(() =>
                                                               CreateInstance <CreationCountFakeService>(createFunc, serviceProvider));

            Assert.Equal($"Unable to resolve service for type '{typeof(IFakeService)}' while attempting" +
                         $" to activate '{typeof(CreationCountFakeService)}'.",
                         ex.Message);
        }
예제 #27
0
        public void CorrectlyAddsHandlers()
        {
            var fakeCollection = new TestServiceCollection();

            fakeCollection.AddSeaOrDewHandlers(options =>
            {
                options.LoadAllHandlersFromAssembly(TestHandlersAssembly);
            });

            Assert.Contains(fakeCollection, s => s.ServiceType == typeof(CommandHandler));
            Assert.Contains(fakeCollection, s => s.ServiceType == typeof(QueryHandler));
            Assert.Equal(OtherTestsHandlersCount + AssemblyHandlerCount + 2, fakeCollection.Count);
        }
예제 #28
0
        public async void NoSession()
        {
            var collection = new TestServiceCollection();

            collection.AddSingleton(new MockHttpClientFactory().Object);

            collection.AddMemoryCache();

            var serviceProvider = collection.GetServiceProvider();

            var ctrl = serviceProvider.CallConstructorWithDI <SSLCtrlService>(typeof(SSLCtrlService).GetConstructors()[0]);

            await Assert.ThrowsAsync <SessionExpirationException>(() => ctrl.TryDownloadCert(Guid.NewGuid()));
        }
        public void TypeActivatorUsesMarkedConstructor(CreateInstanceFunc createFunc)
        {
            // Arrange
            var serviceCollection = new TestServiceCollection();

            serviceCollection.AddSingleton <IFakeService, FakeService>();
            var serviceProvider = CreateServiceProvider(serviceCollection);

            // Act
            var instance = CreateInstance <ClassWithAmbiguousCtorsAndAttribute>(createFunc, serviceProvider, "hello");

            // Assert
            Assert.Equal("IFakeService, string", instance.CtorUsed);
        }
예제 #30
0
        public void ConstrainedOpenGenericServicesReturnsEmptyWithNoMatches()
        {
            // Arrange
            var collection = new TestServiceCollection();

            collection.AddTransient(typeof(IFakeOpenGenericService <>), typeof(ConstrainedFakeOpenGenericService <>));
            collection.AddSingleton <IFakeSingletonService, FakeService>();
            var provider = CreateServiceProvider(collection);
            // Act
            var constrainedServices = provider.GetServices <IFakeOpenGenericService <IFakeSingletonService> >().ToList();

            // Assert
            Assert.Equal(0, constrainedServices.Count);
        }