当前位置: 首页>>代码示例>>C#>>正文


C# ServiceCollection.AddScoped方法代码示例

本文整理汇总了C#中ServiceCollection.AddScoped方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddScoped方法的具体用法?C# ServiceCollection.AddScoped怎么用?C# ServiceCollection.AddScoped使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ServiceCollection的用法示例。


在下文中一共展示了ServiceCollection.AddScoped方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CommandManagerTests

        public CommandManagerTests()
        {
            var services = new ServiceCollection();

            services.AddScoped<ICommandManager, DefaultCommandManager>();
            services.AddScoped<ICommandHandler, MyCommand>();

            _manager = services.BuildServiceProvider().GetService<ICommandManager>();
        }
开发者ID:adwardliu,项目名称:Orchard2,代码行数:9,代码来源:CommandManagerTests.cs

示例2: InMemoryFixture

        public InMemoryFixture()
        {
            var services = new ServiceCollection();

            services
                .AddEntityFramework()
                .AddInMemoryDatabase()
                .AddDbContext<TestDbContext>(options =>
                    options.UseInMemoryDatabase()
                );

            services.AddScoped<IExternalAuditStoreProvider, TestableDbAuditStoreProvider>();
            services.AddScoped<IAuditLogBuilder, CustomAuditLogBuilder>();

            _serviceProvider = services.BuildServiceProvider();
        }
开发者ID:oconics,项目名称:EFAuditing,代码行数:16,代码来源:InMemoryFixture.cs

示例3: AddOrchardLogging

        public static ILoggerFactory AddOrchardLogging(
            this ILoggerFactory loggingFactory, 
            IServiceProvider serviceProvider)
        {
            /* TODO (ngm): Abstract this logger stuff outta here! */
            var loader = serviceProvider.GetRequiredService<IExtensionLoader>();
            var manager = serviceProvider.GetRequiredService<IExtensionManager>();

            var descriptor = manager.GetExtension("Orchard.Logging.Console");
            var entry = loader.Load(descriptor);
            var loggingInitiatorTypes = entry
                .Assembly
                .ExportedTypes
                .Where(et => typeof(ILoggingInitiator).IsAssignableFrom(et));

            IServiceCollection loggerCollection = new ServiceCollection();
            foreach (var initiatorType in loggingInitiatorTypes) {
                loggerCollection.AddScoped(typeof(ILoggingInitiator), initiatorType);
            }
            var moduleServiceProvider = serviceProvider.CreateChildContainer(loggerCollection).BuildServiceProvider();
            foreach (var service in moduleServiceProvider.GetServices<ILoggingInitiator>()) {
                service.Initialize(loggingFactory);
            }

            return loggingFactory;
        }
开发者ID:SmartFire,项目名称:Orchard2,代码行数:26,代码来源:LoggerFactoryExtensions.cs

示例4: ShapeFactoryTests

        public ShapeFactoryTests()
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped<ILoggerFactory, StubLoggerFactory>();
            serviceCollection.AddScoped<IShapeFactory, DefaultShapeFactory>();
            serviceCollection.AddScoped<IExtensionManager, StubExtensionManager>();
            serviceCollection.AddScoped<IShapeTableManager, TestShapeTableManager>();

            var defaultShapeTable = new ShapeTable {
                Descriptors = new Dictionary<string, ShapeDescriptor>(StringComparer.OrdinalIgnoreCase),
                Bindings = new Dictionary<string, ShapeBinding>(StringComparer.OrdinalIgnoreCase)
            };
            serviceCollection.AddInstance(defaultShapeTable);

            _serviceProvider = serviceCollection.BuildServiceProvider();
        }
开发者ID:freemsly,项目名称:Orchard2,代码行数:17,代码来源:ShapeFactoryTests.cs

示例5: CreateContainer

        public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            // Sure this is right?
            serviceCollection.AddInstance(_loggerFactory);

            IServiceCollection moduleServiceCollection = new ServiceCollection();
            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) {

                moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type);
            }

            var moduleServiceProvider = moduleServiceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
            foreach (var service in moduleServiceProvider.GetServices<IModule>()) {
                service.Configure(serviceCollection);
            }

            foreach (var dependency in blueprint.Dependencies
                .Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    _logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);

                    if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddSingleton(interfaceType, dependency.Type);
                    }
                    else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                    else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) {
                        serviceCollection.AddTransient(interfaceType, dependency.Type);
                    }
                    else {
                        serviceCollection.AddScoped(interfaceType, dependency.Type);
                    }
                }
            }

            return serviceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
        }
开发者ID:nicklv,项目名称:Orchard2,代码行数:46,代码来源:ShellContainerFactory.cs

示例6: InMemoryFixture

        public InMemoryFixture()
        {
            var services = new ServiceCollection();

            services
                .AddEntityFramework()
                .AddInMemoryDatabase()
                .AddDbContext<CoffeeStoreContext>(options =>
                    options.UseInMemoryDatabase()
                );

            services.AddScoped<ICoffeeStoreContext>(provider => provider.GetService<CoffeeStoreContext>());
            services.AddScoped<IPriceService, PriceService>();

            // services.AddInstance<>  // Wire-up logging

            _serviceProvider = services.BuildServiceProvider();
        }
开发者ID:dneimke,项目名称:coffeestore,代码行数:18,代码来源:InMemoryFixture.cs

示例7: BuildMediator

        private static IMediator BuildMediator()
        {
            var services = new ServiceCollection();

            services.AddScoped<SingleInstanceFactory>(p => t => p.GetRequiredService(t));
            services.AddScoped<MultiInstanceFactory>(p => t => p.GetRequiredServices(t));

            services.AddSingleton(Console.Out);

            // Use Scrutor to scan and register all
            // classes as their implemented interfaces.
            services.Scan(scan => scan
                .FromAssembliesOf(typeof(IMediator), typeof(Ping))
                .AddClasses()
                .AsImplementedInterfaces());

            var provider = services.BuildServiceProvider();

            return provider.GetRequiredService<IMediator>();
        }
开发者ID:x4maT,项目名称:MediatR,代码行数:20,代码来源:Program.cs

示例8: GetService_throws_useful_exception_if_resolution_fails

        public void GetService_throws_useful_exception_if_resolution_fails()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddScoped<IPilkington, Karl>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Assert.Equal(
                KarlQuote,
                Assert.Throws<NotSupportedException>(
                    () => serviceProvider.GetService<IPilkington>()).Message);
        }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:11,代码来源:ServiceProviderExtensionsTest.cs

示例9: AddCaching_DoesNotReplaceUserRegisteredServices

        public void AddCaching_DoesNotReplaceUserRegisteredServices()
        {
            // Arrange
            var services = new ServiceCollection();
            services.AddScoped<IMemoryCache, TestMemoryCache>();
            services.AddScoped<IDistributedCache, TestDistributedCache>();

            // Act
            services.AddCaching();

            // Assert
            var serviceProvider = services.BuildServiceProvider();
            var memoryCache = services.FirstOrDefault(desc => desc.ServiceType == typeof(IMemoryCache));
            Assert.NotNull(memoryCache);
            Assert.Equal(ServiceLifetime.Scoped, memoryCache.Lifetime);
            Assert.IsType<TestMemoryCache>(serviceProvider.GetRequiredService<IMemoryCache>());

            var distributedCache = services.FirstOrDefault(desc => desc.ServiceType == typeof(IDistributedCache));
            Assert.NotNull(distributedCache);
            Assert.Equal(ServiceLifetime.Scoped, memoryCache.Lifetime);
            Assert.IsType<TestDistributedCache>(serviceProvider.GetRequiredService<IDistributedCache>());
        }
开发者ID:andyshao,项目名称:Caching,代码行数:22,代码来源:CacheServiceExtensionsTests.cs

示例10: ConfigureServices

        private void ConfigureServices(ServiceCollection services)
        {
            var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<CoffeeStoreContext>(options =>
                {
                    options.UseSqlServer(connectionString);
                }
                );

            services.AddScoped<ICoffeeStoreContext>(provider => provider.GetService<CoffeeStoreContext>());
        }
开发者ID:dneimke,项目名称:coffeestore,代码行数:13,代码来源:Program.cs

示例11: DefaultServices

        public static IServiceCollection DefaultServices()
        {
            var services = new ServiceCollection();

            services.AddTransient<IFakeService, FakeService>();
            services.AddTransient<IFakeMultipleService, FakeOneMultipleService>();
            services.AddTransient<IFakeMultipleService, FakeTwoMultipleService>();
            services.AddTransient<IFakeOuterService, FakeOuterService>();
            services.AddInstance<IFakeServiceInstance>(new FakeService() { Message = "Instance" });
            services.AddScoped<IFakeScopedService, FakeService>();
            services.AddSingleton<IFakeSingletonService, FakeService>();
            services.AddTransient<IDependOnNonexistentService, DependOnNonexistentService>();
            services.AddTransient<IFakeOpenGenericService<string>, FakeService>();
            services.AddTransient(typeof(IFakeOpenGenericService<>), typeof(FakeOpenGenericService<>));

            services.AddTransient<IFactoryService>(provider =>
            {
                var fakeService = provider.GetService<IFakeService>();
                return new TransientFactoryService
                {
                    FakeService = fakeService,
                    Value = 42
                };
            });

            services.AddScoped(provider =>
            {
                var fakeService = provider.GetService<IFakeService>();
                return new ScopedFactoryService
                {
                    FakeService = fakeService,
                };
            });
            services.AddScoped<ClassWithNestedReferencesToProvider>();

            services.AddTransient<ServiceAcceptingFactoryService, ServiceAcceptingFactoryService>();
            return services;
        }
开发者ID:winlee,项目名称:DependencyInjection,代码行数:38,代码来源:TestServices.cs

示例12: ConfigureServices

        private static IServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddLogging();

            services.AddSleeper(sleeper =>
            {
                sleeper.AddSqlServer(p => new SqlConnection(connectionString));
                sleeper.AddService<WindowsServiceInitiatorService>();
                sleeper.AddService<WindowsServiceTargetService>();
            });

            services.AddScoped<InitiatorQueueWorker>();
            services.AddScoped<TargetQueueWorker>();

            var provider = services.BuildServiceProvider();

            var logging = provider.GetRequiredService<ILoggerFactory>();

            logging.AddConsole();

            return provider;
        }
开发者ID:tuespetre,项目名称:Sleeper,代码行数:24,代码来源:Program.cs

示例13: GetDefaultServices

        public static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType = null)
        {
            Type userStoreType;
            Type roleStoreType;
            if (keyType != null)
            {
                userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType);
                roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType);
            }
            else
            {
                userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, contextType);
                roleStoreType = typeof(RoleStore<,>).MakeGenericType(roleType, contextType);
            }

            var services = new ServiceCollection();
            services.AddScoped(
                typeof(IUserStore<>).MakeGenericType(userType),
                userStoreType);
            services.AddScoped(
                typeof(IRoleStore<>).MakeGenericType(roleType),
                roleStoreType);
            return services;
        }
开发者ID:staff0rd,项目名称:entityframework-identity,代码行数:24,代码来源:IdentityEntityFrameworkServices.cs

示例14: UsesServiceProviderToDisccoverEntities

        public void UsesServiceProviderToDisccoverEntities()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddEntityFrameworkInMemoryDatabase()
                .AddDbContext<DbContext>((sp, x) => x.UseInMemoryDatabase().UseInternalServiceProvider(sp));
            serviceCollection.ConfigureEntityFramework(f => f.Using().UseConvention<DependingConvention>());
            serviceCollection.AddScoped<Dependency>();
            var provider = serviceCollection.BuildServiceProvider();

            var dbContext = provider.GetService<DbContext>();

            var model = dbContext.Model;

            Assert.Equal(typeof(EntityOne), model.GetEntityTypes().First().ClrType);
        }
开发者ID:Grinderofl,项目名称:FluentModelBuilder,代码行数:15,代码来源:BuildingUsingServiceProviderScoped.cs

示例15: Main

 public static void Main(string[] args)
 {
     var services = new ServiceCollection();
     services.AddEntityFramework().AddInMemoryDatabase();
     services.AddScoped(sp => new TestContext(sp));
     var serviceProvider = services.BuildServiceProvider();
     using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
     {
         // Works
         var results = scope.ServiceProvider.GetRequiredService<TestContext>().Widgets.Where(GetNewExpression(true)).ToList();
     }
     using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
     {
         // Breaks
         var results = scope.ServiceProvider.GetRequiredService<TestContext>().Widgets.Where(GetNewExpression(false)).ToList();
     }
 }
开发者ID:EricABC,项目名称:EFBugReproIssue4549,代码行数:17,代码来源:Program.cs


注:本文中的ServiceCollection.AddScoped方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。