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


C# ServiceCollection.AddScoped方法代码示例

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


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

示例1: TestHelloNonGenericServiceDecoratorNoInterface

        public void TestHelloNonGenericServiceDecoratorNoInterface()
        {
            var services = new ServiceCollection();

            services.AddInstance<IHelloService>(new HelloService());

            services.AddSingleton<IHelloService>(sp => new HelloService());
            services.AddScoped<IHelloService>(sp => new HelloService());
            services.AddTransient<IHelloService>(sp => new HelloService());

            services.AddSingleton<IHelloService, HelloService>();
            services.AddScoped<IHelloService, HelloService>();
            services.AddTransient<IHelloService, HelloService>();

            services.AddDecorator(typeof(IHelloService), (sp, s) => new HelloServiceDecoratorNoInterface((IHelloService)s));

            var provider = services.BuildServiceProvider();

            var helloServices = provider.GetRequiredServices<IHelloService>();
            Assert.NotNull(helloServices);
            var collection = helloServices as IHelloService[] ?? helloServices.ToArray();
            Assert.Equal(7, collection.Length);
            Assert.NotEmpty(collection);
            foreach (var helloService in collection)
            {
                Assert.NotNull(helloService);
                Assert.Equal("Decorated without interface: Hello world.", helloService.SayHello("world"));
            }
        }
开发者ID:sherif-elmetainy,项目名称:DI,代码行数:29,代码来源:DecoratorTests.cs

示例2: Build

        public static IServiceProvider Build()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped<IAppDataDirectory, AppDataDirectory>();
            serviceCollection.AddScoped<IRootDirectory, RootDirectory>();

            return serviceCollection.BuildServiceProvider();
        }
开发者ID:jango2015,项目名称:Rabbit,代码行数:9,代码来源:RabbitStarter.cs

示例3: CreateContainer

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

            serviceCollection.AddScoped<IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped<IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            foreach (var dependency in blueprint.Dependencies
                .Where(t => typeof (IModule).IsAssignableFrom(t.Type))) {

                Logger.Debug("IModule Type: {0}", dependency.Type);

                // TODO: Rewrite to get rid of reflection.
                var instance = (IModule) Activator.CreateInstance(dependency.Type);
                instance.Configure(serviceCollection);
            }

            var p = _serviceProvider.GetService<IOrchardLibraryManager>();
            serviceCollection.AddInstance<IAssemblyProvider>(new DefaultAssemblyProviderTest(p, _serviceProvider, _serviceProvider.GetService<IAssemblyLoaderContainer>()));

            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.Debug("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);
                    }
                }
            }

            serviceCollection.AddLogging();

            return new WrappingServiceProvider(_serviceProvider, serviceCollection);
        }
开发者ID:fengyeju,项目名称:Brochard,代码行数:54,代码来源:ShellContainerFactory.cs

示例4: SqliteMetadataModelProviderTest

        public SqliteMetadataModelProviderTest()
        {
            _testStore = SqliteTestStore.CreateScratch();
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddLogging();
            new SqliteDesignTimeMetadataProviderFactory().AddMetadataProviderServices(serviceCollection);
            serviceCollection.AddScoped(typeof(ILogger), sp => { return _logger = new TestLogger(); });
            serviceCollection.AddScoped<IFileService, FileSystemFileService>();

            _metadataModelProvider = serviceCollection
                .BuildServiceProvider()
                .GetService<IDatabaseMetadataModelProvider>() as SqliteMetadataModelProvider;
        }
开发者ID:rbenhassine2,项目名称:EntityFramework,代码行数:13,代码来源:SqliteMetadataModelProviderTest.cs

示例5: CreateContainer

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

            serviceCollection.AddScoped<IOrchardShell, DefaultOrchardShell>();
            serviceCollection.AddScoped<IRouteBuilder, DefaultShellRouteBuilder>();
            serviceCollection.AddInstance(settings);
            serviceCollection.AddInstance(blueprint.Descriptor);
            serviceCollection.AddInstance(blueprint);

            serviceCollection.AddMvc();

            serviceCollection.Configure<RazorViewEngineOptions>(options => {
                var expander = new ModuleViewLocationExpander();
                options.ViewLocationExpanders.Add(expander);
            });

            var p = _serviceProvider.GetService<IOrchardLibraryManager>();
            serviceCollection.AddInstance<IAssemblyProvider>(new DefaultAssemblyProviderTest(p, _serviceProvider, _serviceProvider.GetService<IAssemblyLoaderContainer>()));

            foreach (var dependency in blueprint.Dependencies) {
                foreach (var interfaceType in dependency.Type.GetInterfaces()
                    .Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
                    Logger.Debug("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);
                    }
                }
            }

            //foreach (var item in blueprint.Controllers) {
            //    var serviceKeyName = (item.AreaName + "/" + item.ControllerName).ToLowerInvariant();
            //    var serviceKeyType = item.Type;
            //    serviceCollection.AddScoped(serviceKeyType);

            //}

            return BuildFallbackServiceProvider(
                            serviceCollection,
                            _serviceProvider);
        }
开发者ID:night-king,项目名称:OrchardNoCMS,代码行数:50,代码来源:ShellContainerFactory.cs

示例6: GetDefaultServices

        public static IServiceCollection GetDefaultServices(
            Type userType, Type roleType, Type contextType, IConfiguration config = null)
        {
            Type userStoreType = typeof(UserStore<,,>).MakeGenericType(userType, roleType, contextType);
            Type roleStoreType = typeof(RoleStore<,,>).MakeGenericType(userType, roleType, contextType);

            var services = new ServiceCollection();
            services.AddScoped(
                typeof(IUserStore<>).MakeGenericType(userType),
                userStoreType);
            services.AddScoped(
                typeof(IRoleStore<>).MakeGenericType(roleType),
                roleStoreType);
            return services;
        }
开发者ID:gavynriebau,项目名称:AspNet.Identity3.MongoDB,代码行数:15,代码来源:MongoIdentityServices.cs

示例7: AddOrchardLogging

        public static ILoggerFactory AddOrchardLogging(
            [NotNull] 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 = loggerCollection.BuildShellServiceProviderWithHost(serviceProvider);
            foreach (var service in moduleServiceProvider.GetServices<ILoggingInitiator>()) {
                service.Initialize(loggingFactory);
            }

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

示例8: DefineServices

 public IServiceCollection DefineServices()
 {
     var services = new ServiceCollection();
     services.AddSingleton<ICall, CallOne>();
     services.AddScoped<ICall, CallTwo>();
     services.AddTransient<ICall, CallThree>();
     
     return services;
 }
开发者ID:Tragetaschen,项目名称:Entropy,代码行数:9,代码来源:Startup.cs

示例9: CreateServiceProvider

        protected /*override*/ IServiceProvider CreateServiceProvider(bool throwingStateManager = false)
        {
            var serviceCollection = new ServiceCollection().AddEntityFramework().AddSQLite().ServiceCollection;

            if (throwingStateManager)
            {
                serviceCollection.AddScoped<StateManager, ThrowingMonsterStateManager>();
            }

            return serviceCollection.BuildServiceProvider();
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:11,代码来源:MonsterFixupTest.cs

示例10: CreateServiceProvider

        protected override IServiceProvider CreateServiceProvider(bool throwingStateManager = false)
        {
            var serviceCollection = new ServiceCollection().AddEntityFramework().AddInMemoryDatabase().ServiceCollection();

            if (throwingStateManager)
            {
                serviceCollection.AddScoped<IStateManager, ThrowingMonsterStateManager>();
            }

            return serviceCollection.BuildServiceProvider();
        }
开发者ID:491134648,项目名称:EntityFramework,代码行数:11,代码来源:MonsterFixupInMemoryTest.cs

示例11: 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:thegido,项目名称:EntityFramework,代码行数:11,代码来源:ServiceProviderExtensionsTest.cs

示例12: 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:BrisWhite,项目名称:Caching,代码行数:22,代码来源:CacheServiceExtensionsTests.cs

示例13: 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:rgmills,项目名称:Autofac,代码行数:38,代码来源:TestServices.cs

示例14: GetDefaultServices

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

            var services = new ServiceCollection();
            services.AddScoped(
                typeof(IUserStore<>).MakeGenericType(userType),
                userStoreType);
            services.AddScoped(
                typeof(IRoleStore<>).MakeGenericType(roleType),
                roleStoreType);
            return services;
        }
开发者ID:hiiru,项目名称:AspNet.Identity.DocumentDb,代码行数:23,代码来源:IdentityDocumentDbServices.cs

示例15: 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);
            }

            foreach (var service in moduleServiceCollection.BuildServiceProvider().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:jrestall,项目名称:Brochard,代码行数:45,代码来源:ShellContainerFactory.cs


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