Ejemplo n.º 1
0
 // This method gets called by the runtime.
 public void ConfigureServices(IServiceCollection services)
 {
     // Add MVC services to the services container.
     services.AddMvc();
     var d = new ServiceDescriptor(typeof(IUnitOfWork), new UnitOfWork());
     services.Add(d);
 }
Ejemplo n.º 2
0
        private static Lazy<object> GetLazyForService(IServiceProvider services, ServiceDescriptor descriptor)
        {
            CryptoUtil.Assert(descriptor != null && descriptor.Lifetime == ServiceLifetime.Singleton, "Descriptor must represent singleton.");
            CryptoUtil.Assert(descriptor.ImplementationFactory != null, "Descriptor must have an implementation factory.");

            // pull the factory out so we don't close over the whole descriptor instance
            Func<IServiceProvider, object> wrapped = descriptor.ImplementationFactory;
            return new Lazy<object>(() => wrapped(services));
        }
Ejemplo n.º 3
0
        public void CanGenerateFactoryService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IService), typeof(Service), ServiceLifetime.Transient);
            builder.Populate(new ServiceDescriptor[] {descriptor});
            var container = builder.Build();

            container.AssertRegistered<Func<IService>>();
        }
        /// <summary>
        /// Adds warcraft services to the collection
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddWarcraft(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.TryAddDefaultServices();
            var descriptor = new ServiceDescriptor(typeof(WarcraftClient), typeof(WarcraftClient), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);
            return services;
        }
Ejemplo n.º 5
0
        public void CanRegisterFactoryService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IService), sp => new Service(), LifecycleKind.Transient);
            builder.Populate(new IServiceDescriptor[] {descriptor});
            var container = builder.Build();

            container.AssertRegistered<Func<IServiceProvider, IService>>();
        }
Ejemplo n.º 6
0
        public void CanRegisterGenericService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IList<>), typeof(List<>), LifecycleKind.Scoped);
            builder.Populate(new IServiceDescriptor[] { descriptor });
            var container = builder.Build();

            container.AssertRegistered<IList<IService>>();
        }
        /// <summary>
        /// Adds <see cref="DefaultRegionSelector"/> to the service collection
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private static IServiceCollection TryAddDefaultServices(this IServiceCollection services)
        {
            var descriptor = new ServiceDescriptor(typeof(IRegionSelector), DefaultRegionSelector.DefaultInstance);
            services.TryAdd(descriptor);

            descriptor = new ServiceDescriptor(typeof(IBattleNetAccessTokenAccessor), typeof(BattleNetAccessTokenAccessor), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);
            return services;
        }
Ejemplo n.º 8
0
        public void CanRegisterSingletonService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IService), typeof(Service), LifecycleKind.Singleton);
            builder.Populate(new IServiceDescriptor[] {descriptor});
            var container = builder.Build();

            container.AssertLifetime<IService, RootScopeLifetime>();
            container.AssertSharing<IService>(InstanceSharing.Shared);
            container.AssertOwnership<IService>(InstanceOwnership.OwnedByLifetimeScope);
        }
Ejemplo n.º 9
0
        public DefaultKeyServices(IServiceProvider services, ServiceDescriptor keyEncryptorDescriptor, ServiceDescriptor keyRepositoryDescriptor)
        {
            if (keyEncryptorDescriptor != null)
            {
                // optional
                CryptoUtil.Assert(keyEncryptorDescriptor.ServiceType == typeof(IXmlEncryptor), "Bad service type.");
                _keyEncryptorLazy = GetLazyForService(services, keyEncryptorDescriptor);
            }

            CryptoUtil.Assert(keyRepositoryDescriptor.ServiceType == typeof(IXmlRepository), "Bad service type.");
            _keyRepositoryLazy = GetLazyForService(services, keyRepositoryDescriptor);
        }
        /// <summary>
        /// Adds warcraft services to the collection
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddBattleNetCache(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddCaching();
            services.TryAddDefaultServices();
            var descriptor = new ServiceDescriptor(typeof(IBattleNetCache), typeof(BattleNetMemoryCache), ServiceLifetime.Singleton);
            services.TryAdd(descriptor);

            descriptor = new ServiceDescriptor(typeof(IBattleNetCachePolicy), typeof(AttributesBattleNetCachePolicy), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);
            return services;
        }
        public void Add_AddsDescriptorToServiceDescriptors()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            var descriptor = new ServiceDescriptor(typeof(IFakeService), new FakeService());

            // Act
            serviceCollection.Add(descriptor);

            // Assert
            var result = Assert.Single(serviceCollection);
            Assert.Same(result, descriptor);
        }
        public void Add_AddsMultipleDescriptorToServiceDescriptors()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService());
            var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient);

            // Act
            serviceCollection.Add(descriptor1);
            serviceCollection.Add(descriptor2);

            // Assert
            Assert.Equal(2, serviceCollection.Count);
            Assert.Equal(new[] { descriptor1, descriptor2 }, serviceCollection);
        }
        public void ServiceDescriptors_AllowsRemovingPreviousRegisteredServices()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService());
            var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient);

            // Act
            serviceCollection.Add(descriptor1);
            serviceCollection.Add(descriptor2);
            serviceCollection.Remove(descriptor1);

            // Assert
            var result = Assert.Single(serviceCollection);
            Assert.Same(result, descriptor2);
        }
        /// <summary>
        /// Adds default services to the service collection
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private static IServiceCollection TryAddDefaultServices(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            services.AddLogging();
            services.AddDataProtection();

            var descriptor = new ServiceDescriptor(typeof(IAuthenticatorDataRepository), typeof(UserProfileAuthenticatorDataRepository), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);

            descriptor = new ServiceDescriptor(typeof(IEnrollmentClient), typeof(EnrollmentClient), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);

            descriptor = new ServiceDescriptor(typeof(IAuthenticator), typeof(Authenticator), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);

            return services;
        }
        private static void Register(IUnityContainer container,
            ServiceDescriptor descriptor)
        {
            if (descriptor.ImplementationType != null)
            {
                container.RegisterType(descriptor.ServiceType,
                    descriptor.ImplementationType,
                    GetLifetimeManager(descriptor.Lifetime));

                container.RegisterType(descriptor.ServiceType,
                    descriptor.ImplementationType,
                    descriptor.ImplementationType.ToString(),
                    GetLifetimeManager(descriptor.Lifetime));
            }
            else if (descriptor.ImplementationFactory != null)
            {
                container.RegisterType(descriptor.ServiceType,
                    GetLifetimeManager(descriptor.Lifetime),
                    new InjectionFactory(unity =>
                    {
                        var provider = unity.Resolve<IServiceProvider>();
                        return descriptor.ImplementationFactory(provider);
                    }));

                container.RegisterType(descriptor.ServiceType,
                    Guid.NewGuid().ToString(),
                    GetLifetimeManager(descriptor.Lifetime),
                    new InjectionFactory(unity =>
                    {
                        var provider = unity.Resolve<IServiceProvider>();
                        return descriptor.ImplementationFactory(provider);
                    }));
            }
            else if (descriptor.ImplementationInstance != null)
            {
                container.RegisterInstance(descriptor.ServiceType,
                    descriptor.ImplementationInstance,
                    GetLifetimeManager(descriptor.Lifetime));

                container.RegisterInstance(descriptor.ServiceType,
                    Guid.NewGuid().ToString(),
                    descriptor.ImplementationInstance,
                    GetLifetimeManager(descriptor.Lifetime));
            }
        }
Ejemplo n.º 16
0
 private static void Use(GenericFamilyExpression expression, ServiceDescriptor descriptor)
 {
     if (descriptor.ImplementationFactory != null)
     {
         expression.Use(Guid.NewGuid().ToString(), context => { return descriptor.ImplementationFactory(context.GetInstance<IServiceProvider>()); });
     }
     else if (descriptor.ImplementationInstance != null)
     {
         expression.Use(descriptor.ImplementationInstance);
     }
     else if (descriptor.ImplementationType != null)
     {
         expression.Use(descriptor.ImplementationType);
     }
     else
     {
         throw new InvalidOperationException("IServiceDescriptor is invalid");
     }
 }
        private void Register(ServiceDescriptor descriptor)
        {
            if (descriptor.ImplementationType != null)
            {
                For(descriptor.ServiceType)
                    .LifecycleIs(descriptor.Lifetime)
                    .Use(descriptor.ImplementationType);

                return;
            }

            if (descriptor.ImplementationFactory != null)
            {
                For(descriptor.ServiceType)
                    .LifecycleIs(descriptor.Lifetime)
                    .Use(CreateFactory(descriptor));

                return;
            }

            For(descriptor.ServiceType)
                .LifecycleIs(descriptor.Lifetime)
                .Use(descriptor.ImplementationInstance);
        }
Ejemplo n.º 18
0
 // Internal for testing.
 internal static void AddXmlSerializerFormatterServices(IServiceCollection services)
 {
     services.TryAddEnumerable(
         ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcXmlSerializerMvcOptionsSetup>());
 }
Ejemplo n.º 19
0
        // This method gets called by the runtime.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));

            // Add MVC services to the services container.
            services.AddMvc();
            var d = new ServiceDescriptor(typeof(IUnitOfWork), new UnitOfWork());
            services.Add(d);
        }
        public void TryAddEnumerable_ThrowsWhenAddingIndistinguishableImplementationType(
            ServiceDescriptor descriptor,
            Type serviceType,
            Type implementationType)
        {
            // Arrange
            var collection = new ServiceCollection();

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => collection.TryAddEnumerable(descriptor),
                "descriptor",
                AbstractionResources.FormatTryAddIndistinguishableTypeToEnumerable(implementationType, serviceType));
        }
        public void TryAddEnumerable_DoesNotAddDuplicate(
            ServiceDescriptor descriptor,
            Type expectedServiceType,
            Type expectedImplementationType,
            ServiceLifetime expectedLifetime)
        {
            // Arrange
            var collection = new ServiceCollection();
            collection.TryAddEnumerable(descriptor);

            // Act
            collection.TryAddEnumerable(descriptor);

            // Assert
            var d = Assert.Single(collection);
            Assert.Equal(expectedServiceType, d.ServiceType);
            Assert.Equal(expectedImplementationType, d.GetImplementationType());
            Assert.Equal(expectedLifetime, d.Lifetime);
        }
        public void Replace_ReplacesFirstServiceWithMatchingServiceType()
        {
            // Arrange
            var collection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
            var descriptor2 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
            collection.Add(descriptor1);
            collection.Add(descriptor2);
            var descriptor3 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Singleton);

            // Act
            collection.Replace(descriptor3);

            // Assert
            Assert.Equal(new[] { descriptor2, descriptor3 }, collection);
        }
        public void Replace_AddsServiceIfServiceTypeIsNotRegistered()
        {
            // Arrange
            var collection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
            var descriptor2 = new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeOuterService), ServiceLifetime.Transient);
            collection.Add(descriptor1);

            // Act
            collection.Replace(descriptor2);

            // Assert
            Assert.Equal(new[] { descriptor1, descriptor2 }, collection);
        }
        public void GetImplementationType_ThrowsForNoImplementationType()
        {
            // Arrange
            var serviceType = typeof(IFakeService);
            var collection = new ServiceCollection();
            var descriptor = new ServiceDescriptor(serviceType, null);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => descriptor.GetImplementationType(),
                null,
                AbstractionResources.FormatNoImplementation(serviceType));
        }
        public void AddSequence_AddsServicesToCollection()
        {
            // Arrange
            var collection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
            var descriptor2 = new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeOuterService), ServiceLifetime.Transient);
            var descriptors = new[] { descriptor1, descriptor2 };

            // Act
            var result = collection.Add(descriptors);

            // Assert
            Assert.Equal(descriptors, collection);
        }
Ejemplo n.º 26
0
        public void CanRegisterTransientService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IService), typeof(Service), ServiceLifetime.Transient);
            builder.Populate(new ServiceDescriptor[] {descriptor});
            var container = builder.Build();

            container.AssertLifetime<IService, CurrentScopeLifetime>();
            container.AssertSharing<IService>(InstanceSharing.None);
            container.AssertOwnership<IService>(InstanceOwnership.OwnedByLifetimeScope);
        }
Ejemplo n.º 27
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     var descriptor = new ServiceDescriptor(typeof(IHitCounterService), new HitCounterService(_rootPath));
     services.Add(descriptor);
 }
        /// <summary>
        /// Adds default services to the service collection
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private static void TryAddDefaultServices(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            services.AddLogging();
            services.AddOptions();

            var descriptor = new ServiceDescriptor(typeof(IRegionSelector), DefaultRegionSelector.DefaultInstance);
            services.TryAdd(descriptor);

            descriptor = new ServiceDescriptor(typeof(IBattleNetClient), typeof(BattleNetClient), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);

            descriptor = new ServiceDescriptor(typeof(HttpClient), typeof(HttpClient), ServiceLifetime.Scoped);
            services.TryAdd(descriptor);
        }
 private static long CalculateHash(ServiceDescriptor descriptor)
     => ((((long)descriptor.Lifetime * 397)
          ^ descriptor.ServiceType.GetHashCode()) * 397)
        ^ (descriptor.ImplementationInstance
           ?? descriptor.ImplementationType
           ?? (object)descriptor.ImplementationFactory).GetHashCode();
Ejemplo n.º 30
0
        public static IdentityBuilder AddIdentity <TUser, TRole>(
            this IServiceCollection services,
            Action <IdentityOptions> configureOptions)
            where TUser : class
            where TRole : class
        {
            // Services used by identity
            services.AddOptions();
            services.AddDataProtection();
            services.AddLogging();
            services.TryAdd(ServiceDescriptor.Singleton <IHttpContextAccessor, HttpContextAccessor>());

            // Identity services
            services.TryAdd(ServiceDescriptor.Transient <IUserValidator <TUser>, UserValidator <TUser> >());
            services.TryAdd(ServiceDescriptor.Transient <IPasswordValidator <TUser>, PasswordValidator <TUser> >());
            services.TryAdd(ServiceDescriptor.Transient <IPasswordHasher <TUser>, PasswordHasher <TUser> >());
            services.TryAdd(ServiceDescriptor.Transient <ILookupNormalizer, UpperInvariantLookupNormalizer>());
            services.TryAdd(ServiceDescriptor.Transient <IRoleValidator <TRole>, RoleValidator <TRole> >());
            // No interface for the error describer so we can add errors without rev'ing the interface
            services.TryAdd(ServiceDescriptor.Transient <IdentityErrorDescriber, IdentityErrorDescriber>());
            services.TryAdd(ServiceDescriptor.Scoped <ISecurityStampValidator, SecurityStampValidator <TUser> >());
            services.TryAdd(ServiceDescriptor.Scoped <IUserClaimsPrincipalFactory <TUser>, UserClaimsPrincipalFactory <TUser, TRole> >());
            services.TryAdd(ServiceDescriptor.Scoped <UserManager <TUser>, UserManager <TUser> >());
            services.TryAdd(ServiceDescriptor.Scoped <SignInManager <TUser>, SignInManager <TUser> >());
            services.TryAdd(ServiceDescriptor.Scoped <RoleManager <TRole>, RoleManager <TRole> >());

            if (configureOptions != null)
            {
                services.ConfigureIdentity(configureOptions);
            }
            services.Configure <ExternalAuthenticationOptions>(options =>
            {
                options.SignInScheme = IdentityOptions.ExternalCookieAuthenticationScheme;
            });

            // Configure all of the cookie middlewares
            services.ConfigureIdentityApplicationCookie(options =>
            {
                options.AuthenticationScheme    = IdentityOptions.ApplicationCookieAuthenticationScheme;
                options.AutomaticAuthentication = true;
                options.LoginPath     = new PathString("/Account/Login");
                options.Notifications = new CookieAuthenticationNotifications
                {
                    OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
                };
            });
            services.Configure <CookieAuthenticationOptions>(options =>
            {
                options.AuthenticationScheme    = IdentityOptions.ExternalCookieAuthenticationScheme;
                options.AutomaticAuthentication = false;
                options.CookieName     = IdentityOptions.ExternalCookieAuthenticationScheme;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            }, IdentityOptions.ExternalCookieAuthenticationScheme);
            services.Configure <CookieAuthenticationOptions>(options =>
            {
                options.AuthenticationScheme    = IdentityOptions.TwoFactorRememberMeCookieAuthenticationScheme;
                options.AutomaticAuthentication = false;
                options.CookieName = IdentityOptions.TwoFactorRememberMeCookieAuthenticationScheme;
            }, IdentityOptions.TwoFactorRememberMeCookieAuthenticationScheme);
            services.Configure <CookieAuthenticationOptions>(options =>
            {
                options.AuthenticationScheme    = IdentityOptions.TwoFactorUserIdCookieAuthenticationScheme;
                options.AutomaticAuthentication = false;
                options.CookieName     = IdentityOptions.TwoFactorUserIdCookieAuthenticationScheme;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            }, IdentityOptions.TwoFactorUserIdCookieAuthenticationScheme);

            return(new IdentityBuilder(typeof(TUser), typeof(TRole), services));
        }
        // Adds a service if the service type and implementation type hasn't been added yet. This is needed for
        // services like IConfigureOptions<MvcOptions> or IApplicationModelProvider where you need the ability
        // to register multiple implementation types for the same service type.
        private static bool TryAddMultiRegistrationService(IServiceCollection services, ServiceDescriptor descriptor)
        {
            // This can't work when registering a factory or instance, you have to register a type.
            // Additionally, if any existing registrations use a factory or instance, we can't check those, but we don't
            // assert that because it might be added by user-code.
            Debug.Assert(descriptor.ImplementationType != null);

            if (services.Any(d =>
                d.ServiceType == descriptor.ServiceType &&
                d.ImplementationType == descriptor.ImplementationType))
            {
                return false;
            }

            services.Add(descriptor);
            return true;
        }
Ejemplo n.º 32
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     var d = new ServiceDescriptor(typeof(IUnitOfWork), new UnitOfWork());
     services.Add(d);
 }