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")); } }
public static IServiceProvider Build() { var serviceCollection = new ServiceCollection(); serviceCollection.AddScoped<IAppDataDirectory, AppDataDirectory>(); serviceCollection.AddScoped<IRootDirectory, RootDirectory>(); return serviceCollection.BuildServiceProvider(); }
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); }
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; }
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); }
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; }
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; }
public IServiceCollection DefineServices() { var services = new ServiceCollection(); services.AddSingleton<ICall, CallOne>(); services.AddScoped<ICall, CallTwo>(); services.AddTransient<ICall, CallThree>(); return services; }
protected /*override*/ IServiceProvider CreateServiceProvider(bool throwingStateManager = false) { var serviceCollection = new ServiceCollection().AddEntityFramework().AddSQLite().ServiceCollection; if (throwingStateManager) { serviceCollection.AddScoped<StateManager, ThrowingMonsterStateManager>(); } return serviceCollection.BuildServiceProvider(); }
protected override IServiceProvider CreateServiceProvider(bool throwingStateManager = false) { var serviceCollection = new ServiceCollection().AddEntityFramework().AddInMemoryDatabase().ServiceCollection(); if (throwingStateManager) { serviceCollection.AddScoped<IStateManager, ThrowingMonsterStateManager>(); } return serviceCollection.BuildServiceProvider(); }
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); }
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>()); }
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; }
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; }
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); }
public void Can_specify_connection_in_OnConfiguring() { var serviceCollection = new ServiceCollection(); serviceCollection .AddScoped(p => new SqlConnection(SqlServerNorthwindContext.ConnectionString)) .AddEntityFramework() .AddSqlServer() .AddDbContext<ConnectionInOnConfiguringContext>(); var serviceProvider = serviceCollection.BuildServiceProvider(); using (SqlServerNorthwindContext.GetSharedStore()) { using (var context = serviceProvider.GetRequiredService<ConnectionInOnConfiguringContext>()) { Assert.True(context.Customers.Any()); } } }
public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddInstance(settings); serviceCollection.AddInstance(blueprint.Descriptor); serviceCollection.AddInstance(blueprint); foreach (var dependency in blueprint.Dependencies .Where(t => typeof(IModule).IsAssignableFrom(t.Type))) { _logger.LogDebug("IModule Type: {0}", dependency.Type); ((IModule)ActivatorUtilities .CreateInstance(_serviceProvider, dependency.Type)) .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 new WrappingServiceProvider(_serviceProvider, serviceCollection); }
public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { IServiceCollection serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(); serviceCollection.AddInstance(settings); serviceCollection.AddInstance(blueprint.Descriptor); serviceCollection.AddInstance(blueprint); foreach (var dependency in blueprint.Dependencies .Where(x => x.Type.Name == "ShellStartup" || x.Type.Name == (settings.Name + "ShellStartup"))) { _logger.LogDebug("Shell Startup: {0}", dependency.Type); // TODO: Rewrite to get rid of reflection. var instance = Activator.CreateInstance(dependency.Type); var info = instance.GetType(); info.GetMethod("ConfigureServices").Invoke(instance, new[] { serviceCollection }); } foreach (var dependency in blueprint.Dependencies .Where(t => typeof (IModule).IsAssignableFrom(t.Type))) { _logger.LogDebug("IModule Type: {0}", dependency.Type); // TODO: Rewrite to get rid of reflection. var instance = (IModule) Activator.CreateInstance(dependency.Type); instance.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 new WrappingServiceProvider(_serviceProvider, serviceCollection); }
private static IServiceProvider CreateContextServices(SqlServerTestStore testStore) { var serviceCollection = new ServiceCollection(); serviceCollection .AddEntityFramework() .AddSqlServer(); serviceCollection.AddScoped<SqlServerDatabaseCreator, TestDatabaseCreator>(); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlServer(testStore.Connection.ConnectionString); return ((IAccessor<IServiceProvider>)new BloggingContext( serviceCollection.BuildServiceProvider(), optionsBuilder.Options)) .Service; }
private ServiceCollection SetupInitialServices() { var serviceCollection = new ServiceCollection(); #if DNX451 || DNXCORE50 var manifest = _serviceProvider.GetRequiredService<IServiceManifest>(); if (manifest != null) { foreach (var service in manifest.Services) { serviceCollection.AddTransient( service, sp => _serviceProvider.GetService(service)); } } #endif var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); var logger = loggerFactory.CreateLogger<DatabaseTool>(); serviceCollection.AddScoped(typeof(ILogger), sp => logger); serviceCollection.AddScoped<IFileService, FileSystemFileService>(); return serviceCollection; }
public void Can_select_appropriate_provider_when_multiple_registered() { var serviceCollection = new ServiceCollection(); serviceCollection .AddScoped<SomeService>() .AddEntityFramework() .AddSqlServer() .AddInMemoryDatabase() .AddDbContext<MultipleProvidersContext>(); var serviceProvider = serviceCollection.BuildServiceProvider(); using (SqlServerNorthwindContext.GetSharedStore()) { MultipleProvidersContext context1; MultipleProvidersContext context2; using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { using (context1 = serviceScope.ServiceProvider.GetRequiredService<MultipleProvidersContext>()) { context1.UseSqlServer = true; Assert.True(context1.Customers.Any()); } using (var context1B = serviceScope.ServiceProvider.GetRequiredService<MultipleProvidersContext>()) { Assert.Same(context1, context1B); } var someService = serviceScope.ServiceProvider.GetRequiredService<SomeService>(); Assert.Same(context1, someService.Context); } using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { using (context2 = serviceScope.ServiceProvider.GetRequiredService<MultipleProvidersContext>()) { context2.UseSqlServer = false; Assert.False(context2.Customers.Any()); } using (var context2B = serviceScope.ServiceProvider.GetRequiredService<MultipleProvidersContext>()) { Assert.Same(context2, context2B); } var someService = serviceScope.ServiceProvider.GetRequiredService<SomeService>(); Assert.Same(context2, someService.Context); } Assert.NotSame(context1, context2); } }
public static IServiceCollection GetDefaultServices() { var services = new ServiceCollection(); // Options and core services. services.AddTransient<IConfigureOptions<MvcOptions>, MvcOptionsSetup>(); services.AddTransient<IConfigureOptions<RazorViewEngineOptions>, RazorViewEngineOptionsSetup>(); // TryAdd() so functional tests can override this particular service. Test setup runs before this method. services.TryAdd(ServiceDescriptor.Transient<IAssemblyProvider, DefaultAssemblyProvider>()); services.AddTransient<MvcMarkerService, MvcMarkerService>(); services.AddSingleton<ITypeActivatorCache, DefaultTypeActivatorCache>(); services.AddScoped(typeof(IScopedInstance<>), typeof(ScopedInstance<>)); // Core action discovery, filters and action execution. // These are consumed only when creating action descriptors, then they can be de-allocated services.AddTransient<IControllerTypeProvider, DefaultControllerTypeProvider>(); services.AddTransient<IControllerModelBuilder, DefaultControllerModelBuilder>(); services.AddTransient<IActionModelBuilder, DefaultActionModelBuilder>(); // This has a cache, so it needs to be a singleton services.AddSingleton<IControllerFactory, DefaultControllerFactory>(); services.AddTransient<IControllerActivator, DefaultControllerActivator>(); // This accesses per-reqest services services.AddTransient<IActionInvokerFactory, ActionInvokerFactory>(); // This provider needs access to the per-request services, but might be used many times for a given // request. services.AddTransient<IActionConstraintProvider, DefaultActionConstraintProvider>(); services.AddSingleton<IActionSelectorDecisionTreeProvider, ActionSelectorDecisionTreeProvider>(); services.AddSingleton<IActionSelector, DefaultActionSelector>(); services.AddTransient<IControllerActionArgumentBinder, DefaultControllerActionArgumentBinder>(); services.AddTransient<IObjectModelValidator, DefaultObjectValidator>(); services.AddTransient<IActionDescriptorProvider, ControllerActionDescriptorProvider>(); services.AddTransient<IActionInvokerProvider, ControllerActionInvokerProvider>(); services.AddSingleton<IActionDescriptorsCollectionProvider, DefaultActionDescriptorsCollectionProvider>(); // The IGlobalFilterProvider is used to build the action descriptors (likely once) and so should // remain transient to avoid keeping it in memory. services.AddTransient<IGlobalFilterProvider, DefaultGlobalFilterProvider>(); services.AddTransient<IFilterProvider, DefaultFilterProvider>(); services.AddTransient<FormatFilter, FormatFilter>(); services.AddTransient<CorsAuthorizationFilter, CorsAuthorizationFilter>(); // Dataflow - ModelBinding, Validation and Formatting // // The DefaultModelMetadataProvider does significant caching and should be a singleton. services.AddSingleton<ModelBinding.IModelMetadataProvider, DefaultModelMetadataProvider>(); services.AddTransient<ModelBinding.Metadata.ICompositeMetadataDetailsProvider>(serviceProvider => { var options = serviceProvider.GetRequiredService<IOptions<MvcOptions>>().Options; return new DefaultCompositeMetadataDetailsProvider(options.ModelMetadataDetailsProviders); }); services.AddTransient<IInputFormatterSelector, DefaultInputFormatterSelector>(); services.AddScoped<IInputFormattersProvider, DefaultInputFormattersProvider>(); services.AddTransient<IModelBinderProvider, DefaultModelBindersProvider>(); services.AddTransient<IValueProviderFactoryProvider, DefaultValueProviderFactoryProvider>(); services.AddTransient<IOutputFormattersProvider, DefaultOutputFormattersProvider>(); services.AddInstance(new JsonOutputFormatter()); services.AddTransient<IModelValidatorProviderProvider, DefaultModelValidatorProviderProvider>(); services.AddTransient<IValidationExcludeFiltersProvider, DefaultValidationExcludeFiltersProvider>(); // Razor, Views and runtime compilation // The provider is inexpensive to initialize and provides ViewEngines that may require request // specific services. services.AddScoped<ICompositeViewEngine, CompositeViewEngine>(); services.AddTransient<IViewEngineProvider, DefaultViewEngineProvider>(); // Transient since the IViewLocationExpanders returned by the instance is cached by view engines. services.AddTransient<IViewLocationExpanderProvider, DefaultViewLocationExpanderProvider>(); // Caches view locations that are valid for the lifetime of the application. services.AddSingleton<IViewLocationCache, DefaultViewLocationCache>(); services.AddSingleton<ICodeTreeCache>(serviceProvider => { var cachedFileProvider = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>(); return new DefaultCodeTreeCache(cachedFileProvider.Options.FileProvider); }); // The host is designed to be discarded after consumption and is very inexpensive to initialize. services.AddTransient<IMvcRazorHost, MvcRazorHost>(); // Caches compilation artifacts across the lifetime of the application. services.AddSingleton<ICompilerCache, CompilerCache>(); // This caches compilation related details that are valid across the lifetime of the application // and is required to be a singleton. services.AddSingleton<ICompilationService, RoslynCompilationService>(); // Both the compiler cache and roslyn compilation service hold on the compilation related // caches. RazorCompilation service is just an adapter service, and it is transient to ensure // the IMvcRazorHost dependency does not maintain state. services.AddTransient<IRazorCompilationService, RazorCompilationService>(); // The ViewStartProvider needs to be able to consume scoped instances of IRazorPageFactory services.AddScoped<IViewStartProvider, ViewStartProvider>(); services.AddTransient<IRazorViewFactory, RazorViewFactory>(); services.AddSingleton<IRazorPageActivator, RazorPageActivator>(); // Virtual path view factory needs to stay scoped so views can get get scoped services. services.AddScoped<IRazorPageFactory, VirtualPathRazorPageFactory>(); // View and rendering helpers services.AddTransient<IHtmlHelper, HtmlHelper>(); services.AddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>)); services.AddScoped<IUrlHelper, UrlHelper>(); // Only want one ITagHelperActivator so it can cache Type activation information. Types won't conflict. services.AddSingleton<ITagHelperActivator, DefaultTagHelperActivator>(); // Consumed by the Cache tag helper to cache results across the lifetime of the application. services.AddSingleton<IMemoryCache, MemoryCache>(); // DefaultHtmlGenerator is pretty much stateless but depends on Scoped services such as IUrlHelper and // IActionBindingContextProvider. Therefore it too is scoped. services.AddTransient<IHtmlGenerator, DefaultHtmlGenerator>(); // These do caching so they should stay singleton services.AddSingleton<IViewComponentSelector, DefaultViewComponentSelector>(); services.AddSingleton<IViewComponentActivator, DefaultViewComponentActivator>(); services.AddSingleton<IViewComponentDescriptorCollectionProvider, DefaultViewComponentDescriptorCollectionProvider>(); services.AddTransient<IViewComponentDescriptorProvider, DefaultViewComponentDescriptorProvider>(); services.AddTransient<IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>(); services.AddTransient<IViewComponentHelper, DefaultViewComponentHelper>(); // Security and Authorization services.AddSingleton<IClaimUidExtractor, DefaultClaimUidExtractor>(); services.AddSingleton<AntiForgery, AntiForgery>(); services.AddSingleton<IAntiForgeryAdditionalDataProvider, DefaultAntiForgeryAdditionalDataProvider>(); // Api Description services.AddSingleton<IApiDescriptionGroupCollectionProvider, ApiDescriptionGroupCollectionProvider>(); services.AddTransient<IApiDescriptionProvider, DefaultApiDescriptionProvider>(); // Temp Data services.AddSingleton<ITempDataProvider, SessionStateTempDataProvider>(); services.AddScoped<ITempDataDictionary, TempDataDictionary>(); return services; }
public void TestHelloNonGenericServiceNoDecorator() { var services = new ServiceCollection(); services.AddSingleton<HelloServiceDecorator>(); services.AddScoped<IHelloService>(sp => new HelloService()); services.AddTransient<IHelloService>(sp => new HelloService()); services.AddScoped<IHelloService>(sp => new HelloService()); services.AddTransient<IHelloService>(sp => new HelloService()); services.AddScoped<IHelloService, HelloService>(); services.AddTransient<IHelloService, HelloService>(); services.AddDecorator(typeof(IHelloService), typeof(HelloServiceDecorator)); var provider = services.BuildServiceProvider(); var helloServices = provider.GetRequiredServices<IHelloService>(); Assert.NotNull(helloServices); var collection = helloServices as IHelloService[] ?? helloServices.ToArray(); Assert.NotEmpty(collection); foreach (var helloService in collection) { Assert.NotNull(helloService); Assert.Equal("Hello world.", helloService.SayHello("world")); } }
public async void Can_depend_on_DbContextOptions() { var serviceCollection = new ServiceCollection(); serviceCollection .AddScoped(p => new SqlConnection(SqlServerNorthwindContext.ConnectionString)) .AddEntityFramework() .AddSqlServer() .AddDbContext<OptionsContext>(); var serviceProvider = serviceCollection.BuildServiceProvider(); using (await SqlServerNorthwindContext.GetSharedStoreAsync()) { using (var context = serviceProvider.GetRequiredService<OptionsContext>()) { Assert.True(context.Customers.Any()); } } }
public void TestHelloService() { var services = new ServiceCollection(); services.AddScoped<IHelloService, HelloService>(); var provider = services.BuildServiceProvider(); var helloService = provider.GetRequiredService<IHelloService>(); Assert.NotNull(helloService); var result = helloService.SayHello("world"); Assert.Equal("Hello world.", result); }