ServiceCollectionExtensions

We found 10 examples in language CSharp for this search. You will see 37 fragments of code.
        [Test, CustomAutoMoqData]
        public void ServiceCollection_is_returned(IServiceCollection services, Action<INybusConfigurator> configuratorDelegate)
        {
            var result = ServiceCollectionExtensions.AddNybus(services, configuratorDelegate);

            Assert.That(result, Is.SameAs(services));
        }

        [Test, CustomAutoMoqData]
        public void AddNybus_invokes_configuratorDelegate(IServiceCollection services, Action<INybusConfigurator> configuratorDelegate)
        {
            ServiceCollectionExtensions.AddNybus(services, configuratorDelegate);

            Mock.Get(configuratorDelegate).Verify(p => p(It.IsAny<INybusConfigurator>()));
        }

        [Test, CustomAutoMoqData]
        public void AddNybus_registers_NybusHostOptions(IServiceCollection services, IConfigurationSection configuration, Action<INybusConfigurator> configuratorDelegate)
        {
            ServiceCollectionExtensions.AddNybus(services, configuratorDelegate);

            Mock.Get(services).Verify(p => p.Add(It.Is<ServiceDescriptor>(sd => sd.ServiceType == typeof(NybusHostOptions))));
        }

        [Test, AutoMoqData]
        public void AddCommandHandler_registers_handler_generic_syntax(IServiceCollection services)
        {
            ServiceCollectionExtensions.AddCommandHandler<FirstTestCommand, FirstTestCommandHandler>(services);

            Mock.Get(services).Verify(p => p.Add(It.Is<ServiceDescriptor>(sd => sd.ServiceType == typeof(ICommandHandler<FirstTestCommand>) && sd.ImplementationType == typeof(FirstTestCommandHandler))));
        }

        [Test, AutoMoqData]
        public void AddCommandHandler_registers_handler_by_its_type(IServiceCollection services)
        {
            ServiceCollectionExtensions.AddCommandHandler(services, typeof(FirstTestCommandHandler));

            Mock.Get(services).Verify(p => p.Add(It.Is<ServiceDescriptor>(sd => sd.ServiceType == typeof(ICommandHandler<FirstTestCommand>) && sd.ImplementationType == typeof(FirstTestCommandHandler))));
        }

        [Test, AutoMoqData]
        public void AddCommandHandler_registers_handler_by_its_type_generic_syntax(IServiceCollection services)
        {
            ServiceCollectionExtensions.AddCommandHandler<FirstTestCommandHandler>(services);

            Mock.Get(services).Verify(p => p.Add(It.Is<ServiceDescriptor>(sd => sd.ServiceType == typeof(ICommandHandler<FirstTestCommand>) && sd.ImplementationType == typeof(FirstTestCommandHandler))));
        }


        [Fact]
        public void AddGraphQL_ServicesSchema_ServiceNull()
        {
            // arrange
            var schema = Schema.Create(c => c.Options.StrictValidation = false);

            // act
            Action action = () => ServiceCollectionExtensions.AddGraphQL(
                null, schema);

            // assert
            Assert.Throws<ArgumentNullException>(action);
        }

        [Fact]
        public void AddGraphQL_ServicesSchema_SchemaNull()
        {
            // arrange
            // act
            Action action = () => ServiceCollectionExtensions.AddGraphQL(
                new ServiceCollection(), default(Schema));

            // assert
            Assert.Throws<ArgumentNullException>(action);
        }

        [Fact]
        public void AddGraphQL_ServicesSchemaConfigure_ServiceNull()
        {
            // arrange
            var schema = Schema.Create(c => c.Options.StrictValidation = false);

            // act
            Action action = () => ServiceCollectionExtensions.AddGraphQL(
                null,
                schema,
                new Action<IQueryExecutionBuilder>(c => { }));

            // assert
            Assert.Throws<ArgumentNullException>(action);
        }

        [Fact]
        public void AddGraphQL_ServicesSchemaConfigure_SchemaNull()
        {
            // arrange
            // act
            Action action = () => ServiceCollectionExtensions.AddGraphQL(
                new ServiceCollection(),
                default(Schema),
                new Action<IQueryExecutionBuilder>(c => { }));

            // assert
            Assert.Throws<ArgumentNullException>(action);
        }

        [Fact]
        public void AddGraphQL_ServicesSchemaFactory_ServiceNull()
        {
            // arrange
            var schema = Schema.Create(c => c.Options.StrictValidation = false);

            // act
            Action action = () => ServiceCollectionExtensions.AddGraphQL(
                null, new Func<IServiceProvider, ISchema>(s => schema));

            // assert
            Assert.Throws<ArgumentNullException>(action);
        }

        [Fact]
        public void AddGraphQL_ServicesSchemaFactory_SchemaFactoryNull()
        {
            // arrange
            // act
            Action action = () => ServiceCollectionExtensions.AddGraphQL(
                new ServiceCollection(),
                default(Func<IServiceProvider, ISchema>));

            // assert
            Assert.Throws<ArgumentNullException>(action);
        }

        [Test, CustomAutoData]
        public void AddWcfService_returns_same_ServiceCollection(IServiceCollection services, WcfServiceConfigurator<TestService> configurator, ServiceLifetime lifetime)
        {
            var result = ServiceCollectionExtensions.AddWcfService<TestService>(services, configurator, lifetime);

            Assert.That(result, Is.SameAs(services));
        }

        [Test, CustomAutoData]
        public void AddWcfService_registers_hosted_service(IServiceCollection services, WcfServiceConfigurator<TestService> configurator, ServiceLifetime lifetime)
        {
            ServiceCollectionExtensions.AddWcfService<TestService>(services, configurator, lifetime);

            Mock.Get(services).Verify(p => p.Add(It.Is<ServiceDescriptor>(d => d.ServiceType == typeof(IHostedService) && d.Lifetime == ServiceLifetime.Singleton)));
        }

        [Test, CustomAutoData]
        public void AddWcfService_registers_announcement_service(IServiceCollection services, WcfServiceConfigurator<TestService> configurator, ServiceLifetime lifetime)
        {
            ServiceCollectionExtensions.AddWcfService<TestService>(services, configurator, lifetime);

            Mock.Get(services).Verify(p => p.Add(It.Is<ServiceDescriptor>(d => d.ServiceType == typeof(IAnnouncementService) && d.Lifetime == ServiceLifetime.Singleton)));
        }

        [Test, CustomAutoData]
        public void AddWcfService_throws_if_same_service_registered_twice(ServiceCollection services, WcfServiceConfigurator<TestService> configurator, ServiceLifetime lifetime)
        {
            ServiceCollectionExtensions.AddWcfService<TestService>(services, configurator, lifetime);

            Assert.Throws<ArgumentException>(() => ServiceCollectionExtensions.AddWcfService<TestService>(services, configurator, lifetime));
        }

        [Test, CustomAutoData]
        public void AddDiscovery_returns_service_collection(IServiceCollection services, Uri announcementUri, TimeSpan interval, Action<TestHttpBinding> configureBinding)
        {
            var result = ServiceCollectionExtensions.AddDiscovery(services, announcementUri, interval, configureBinding);

            Assert.That(result, Is.SameAs(services));
        }

        [Test, CustomAutoData]
        public void AddDiscovery_configures_binding_with_delegate(IServiceCollection services, Uri announcementUri, TimeSpan interval, Action<TestBinding> configureBinding)
        {
            var result = ServiceCollectionExtensions.AddDiscovery(services, announcementUri, interval, configureBinding);

            Mock.Get(configureBinding).Verify(p => p(It.IsAny<TestBinding>()));
        }


        public static IServiceCollection AddQueryHandlers(this IServiceCollection services)
        {

            services.Scan(scan => scan
            .FromAssembliesOf(typeof(ServiceCollectionExtensions))
            .AddClasses(classes => classes.AssignableToAny(typeof(IHandleQueryAsync<,>)))
            .AsImplementedInterfaces()
            .WithTransientLifetime());


            return services;
        }

        public static IServiceCollection AddCommandHandlers(this IServiceCollection services)
        {

            services.Scan(scan => scan
                .FromAssembliesOf(typeof(ServiceCollectionExtensions))
                .AddClasses(classes => classes.AssignableToAny(typeof(IAsyncCommandHandler<,>)))
                .AsImplementedInterfaces()
                .WithTransientLifetime()
                );


            return services;
        }


        public static ISitecoreService BuildSitecoreContextService()
        {
            var sitecoreServiceThunk = ServiceCollectionExtensions.Get<Func<Database, ISitecoreService>>();
            return sitecoreServiceThunk(Sitecore.Context.Database);
        }

        public static IRequestContext BuildRequestContext()
        {
            return new RequestContext(ServiceCollectionExtensions.Get<ISitecoreService>());
        }

        public static IGlassHtml BuildGlassHtml()
        {
            return new GlassHtml(ServiceCollectionExtensions.Get<ISitecoreService>());
        }

        public static IMvcContext BuildMvcContext()
        {
            return new MvcContext(ServiceCollectionExtensions.Get<ISitecoreService>(), ServiceCollectionExtensions.Get<IGlassHtml>());
        }


        public static IServiceCollection AddQueryHandlers(this IServiceCollection services)
        {

            services.Scan(scan => scan
            .FromAssembliesOf(typeof(ServiceCollectionExtensions))
            .AddClasses(classes => classes.AssignableToAny(typeof(IHandleQueryAsync<,>)))
            .AsImplementedInterfaces()
            .WithTransientLifetime());


            return services;
        }

        public static IServiceCollection AddCommandHandlers(this IServiceCollection services)
        {

            services.Scan(scan => scan
                .FromAssembliesOf(typeof(ServiceCollectionExtensions))
                .AddClasses(classes => classes.AssignableToAny(typeof(IAsyncCommandHandler<,>)))
                .AsImplementedInterfaces()
                .WithTransientLifetime()
                );


            return services;
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(100);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });
            services.AddCors();
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDefaultIdentity<ApplicationUser>()
               .AddRoles<IdentityRole>()
               .AddEntityFrameworkStores<WpDbContext>();
            services.Configure<IdentityOptions>(options =>
            {
                //// Password settings.
                //options.Password.RequireDigit = true;
                //options.Password.RequireLowercase = true;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequiredLength = 6;
                //options.Password.RequiredUniqueChars = 1;

                //// Lockout settings.
                //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                //options.Lockout.MaxFailedAccessAttempts = 5;
                //options.Lockout.AllowedForNewUsers = true;

                //// User settings.
                //options.User.AllowedUserNameCharacters =
                //"ab[email protected]+";
                //options.User.RequireUniqueEmail = false;
            });

            //services.AddJwt(Configuration); // comment this line out when using mvc views otherwise loging will not work

            services.AddWpAndCatalogDbContexts(Configuration);
            services.AddWp();
            services.AddAutoMapper(typeof(Startup));
            AutoMapperConfiguration.Init();
            services.AddControllersWithViews()
                .AddFluentValidation(opt =>
                {
                    opt.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
                })
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });
            services.AddRazorPages();

            services.AddEasyCaching(option =>
            {
                // use memory cache with a simple way
                option.UseInMemory("default");
            });
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSession();

            ServiceCollectionExtensions.AddLogger();
            ServiceCollectionExtensions.Migrate(app);
            ServiceLocator.Instance = app.ApplicationServices;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }

        public static IServiceCollection AddDb(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext<ProfilingSampleDbContext>(options =>
            {
                options.UseNpgsql(configuration.GetConnectionString(nameof(ProfilingSampleDbContext)));
            });
            return services;
        }

        public static IServiceCollection AddConfiguredMvc(this IServiceCollection services)
        {
            services
                .AddMvc()
                .AddApplicationPart(typeof(ServiceCollectionExtensions).Assembly)
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            return services;
        }

            public void WriteEvent<T>(
                ref T eventData)
                where T : ServiceEventSourceData
            {
                throw new NotImplementedException();
            }

        [Fact]
        public void Should_register_IServiceEventSource_as_Type_and_IServiceEventSource_and_all_IServiceEventSourceInterfaces_When_Adding_IServiceEventSource()
        {
            // Arrange
            var mockServiceCollection = new Mock<IServiceCollection>();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServiceEventSource))))
               .Verifiable();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServiceEventSource))))
               .Verifiable();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IMyServiceEventSourceInterface))))
               .Verifiable();

            var arrangeServiceCollection = mockServiceCollection.Object;

            // Act
            ServiceCollectionExtensions.Add(arrangeServiceCollection, new ServiceEventSource());

            // Assert
            mockServiceCollection.Verify();
        }

        [Fact]
        public void
            Should_register_IServiceHostListenerInformation_as_IServiceHostListenerInformation_and_IServiceHostAspNetCoreListenerInformation_When_Adding_IServiceHostAspNetCoreListenerInformation()
        {
            // Arrange
            var mockServiceCollection = new Mock<IServiceCollection>();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServiceHostListenerInformation))))
               .Verifiable();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServiceHostAspNetCoreListenerInformation))))
               .Verifiable();

            var arrangeServiceCollection = mockServiceCollection.Object;

            // Act
            ServiceCollectionExtensions.Add(arrangeServiceCollection, new AspNetCoreServiceHostListenerInformation());

            // Assert
            mockServiceCollection.Verify();
        }

        [Fact]
        public void
            Should_register_IServiceHostListenerInformation_as_IServiceHostListenerInformation_and_IServiceHostRemotingListenerInformation_When_Adding_IServiceHostRemotingListenerInformation()
        {
            // Arrange
            var mockServiceCollection = new Mock<IServiceCollection>();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServiceHostListenerInformation))))
               .Verifiable();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServiceHostRemotingListenerInformation))))
               .Verifiable();

            var arrangeServiceCollection = mockServiceCollection.Object;

            // Act
            ServiceCollectionExtensions.Add(arrangeServiceCollection, new RemotingServiceHostListenerInformation());

            // Assert
            mockServiceCollection.Verify();
        }

        [Fact]
        public void Should_register_IServicePartition_as_IServicePartition_and_IStatefulServicePartition_When_Adding_IStatefulServicePartition()
        {
            // Arrange
            var mockServiceCollection = new Mock<IServiceCollection>();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServicePartition))))
               .Verifiable();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IStatefulServicePartition))))
               .Verifiable();

            var arrangeServiceCollection = mockServiceCollection.Object;

            // Act
            ServiceCollectionExtensions.Add(arrangeServiceCollection, new MockStatefulServicePartition());

            // Assert
            mockServiceCollection.Verify();
        }

        [Fact]
        public void Should_register_IServicePartition_as_IServicePartition_and_IStatelessServicePartition_When_Adding_IStatelessServicePartition()
        {
            // Arrange
            var mockServiceCollection = new Mock<IServiceCollection>();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IServicePartition))))
               .Verifiable();
            mockServiceCollection
               .Setup(
                    instance => instance.Add(
                        It.Is<ServiceDescriptor>(descriptor => descriptor.ServiceType == typeof(IStatelessServicePartition))))
               .Verifiable();

            var arrangeServiceCollection = mockServiceCollection.Object;

            // Act
            ServiceCollectionExtensions.Add(arrangeServiceCollection, new MockStatelessServicePartition());

            // Assert
            mockServiceCollection.Verify();
        }

        public static IServiceCollection AddEntityFramework(this IServiceCollection services, IConfigurationRoot configuration)
        {
            var dataProviderConfig = configuration.GetSection("Data")["Provider"];
            var connectionStringConfig = configuration.GetConnectionString("DefaultConnection");

            var currentAssembly = typeof(ServiceCollectionExtensions).GetTypeInfo().Assembly;
            var dataProviders = currentAssembly.GetImplementationsOf<IDataProvider>();

            var dataProvider = dataProviders.SingleOrDefault(x => x.Provider.ToString() == dataProviderConfig);

            dataProvider.RegisterDbContext(services, connectionStringConfig);

            //services.AddIdentity<User, Role>()
            //    .AddEntityFrameworkStores<DbContext, Guid>()
            //    .AddDefaultTokenProviders();

            return services;
        }

AspectCore.Extensions.DependencyInjection.ServiceCollectionExtensions : Object

Methods :

public static IServiceCollection AddDynamicProxy(IServiceCollection services = , Action<IAspectConfiguration> configure = null)
public static IServiceCollection ConfigureDynamicProxy(IServiceCollection services = , Action<IAspectConfiguration> configure = null)
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()