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 TestGetStorageConfigurationBadPublicUrlRoot() { var noBucketStorageOptions = new PiranhaS3StorageOptions { BucketName = ValidUnitTestBucketName, KeyPrefix = ValidUnitTestKeyPrefix, PublicUrlRoot = "notaurl" }; try { IServiceCollection services = new ServiceCollection(); var storageFactory = new S3StorageFactory(noBucketStorageOptions, TestFixture.FakeAwsOptions); Func <IServiceProvider, object> factory = storageFactory.CreateS3Storage; services.Add(new ServiceDescriptor(typeof(S3Storage), factory, ServiceLifetime.Singleton)); var serviceProvider = services.BuildServiceProvider(); serviceProvider.GetService <S3Storage>(); Assert.False(true, "Bad PublicUrlRoot did not throw an exception"); } catch (Exception ex) { Assert.IsAssignableFrom <FlagscriptConfigurationException>(ex); } }
public void TestGetStorageConfigurationEnvVarOptions() { try { Environment.SetEnvironmentVariable(PiranhaS3StorageOptions.BucketEnvironmentVariable, "buck"); Environment.SetEnvironmentVariable(PiranhaS3StorageOptions.KeyPrefixEnvironmentVariable, "kp"); Environment.SetEnvironmentVariable(PiranhaS3StorageOptions.UrlRootEnvironmentVariable, "http://flagscript.technology"); IServiceCollection services = new ServiceCollection(); var storageFactory = new S3StorageFactory(null, TestFixture.FakeAwsOptions); Func <IServiceProvider, object> factory = storageFactory.CreateS3Storage; services.Add(new ServiceDescriptor(typeof(S3Storage), factory, ServiceLifetime.Singleton)); var serviceProvider = services.BuildServiceProvider(); var s3Storage = serviceProvider.GetService <S3Storage>(); Assert.Equal("buck", s3Storage.StorageOptions.BucketName); Assert.Equal("kp", s3Storage.StorageOptions.KeyPrefix); Assert.Equal("http://flagscript.technology", s3Storage.StorageOptions.PublicUrlRoot); } finally { Environment.SetEnvironmentVariable(PiranhaS3StorageOptions.BucketEnvironmentVariable, null); Environment.SetEnvironmentVariable(PiranhaS3StorageOptions.KeyPrefixEnvironmentVariable, null); Environment.SetEnvironmentVariable(PiranhaS3StorageOptions.UrlRootEnvironmentVariable, null); } }
public void TestConfigureDependenciesExecutesCorrectlyWhenAssemblyIsSpecified() { // Keep track of the added service descriptors var serviceDescriptors = new List <ServiceDescriptor>(); // Create a mock service collection that wraps a real service collection var serviceCollection = new Mock <IServiceCollection>(); var wrappedServiceCollection = new ServiceCollection(); serviceCollection .Setup(_ => _.Add(It.IsAny <ServiceDescriptor>())) .Callback(( ServiceDescriptor serviceDescriptor ) => { serviceDescriptors.Add(serviceDescriptor); wrappedServiceCollection.Add(serviceDescriptor); }); serviceCollection .Setup(_ => _.GetEnumerator()) .Returns(wrappedServiceCollection.GetEnumerator()); // Configure the service collection using attributes var output = serviceCollection.Object.ConfigureDeclaratively(typeof(One).Assembly); // The same service collection should be returned Assert.Same(output, serviceCollection.Object); // We should expect all the dependencies in the assembly to be added Assert.Equal(4, serviceDescriptors.Count); VerifyServiceDescriptor <IOne, One>(ServiceLifetime.Scoped, serviceDescriptors[0]); VerifyServiceDescriptor <IThreeA, Three>(ServiceLifetime.Singleton, serviceDescriptors[1]); VerifyServiceDescriptor <ITwoA, Two>(ServiceLifetime.Transient, serviceDescriptors[2]); VerifyServiceDescriptor <ITwoB, Two>(ServiceLifetime.Transient, serviceDescriptors[3]); }
public void TestConfigureDependenciesExecutesCorrectlyWhenAssemblyIsNotSpecified() { // Keep track of the added service descriptors var serviceDescriptors = new List <ServiceDescriptor>(); // Create a mock service collection that wraps a real service collection var serviceCollection = new Mock <IServiceCollection>(); var wrappedServiceCollection = new ServiceCollection(); serviceCollection .Setup(_ => _.Add(It.IsAny <ServiceDescriptor>())) .Callback(( ServiceDescriptor serviceDescriptor ) => { serviceDescriptors.Add(serviceDescriptor); wrappedServiceCollection.Add(serviceDescriptor); }); serviceCollection .Setup(_ => _.GetEnumerator()) .Returns(wrappedServiceCollection.GetEnumerator()); // Configure the service collection using attributes var output = serviceCollection.Object.ConfigureDeclaratively(); // The same service collection should be returned Assert.Same(output, serviceCollection.Object); Assert.Equal(4, serviceDescriptors.Count); VerifyServiceDescriptor <IAlpha, Alpha>(ServiceLifetime.Singleton, serviceDescriptors[0]); VerifyServiceDescriptor <IBeta, Beta>(ServiceLifetime.Scoped, serviceDescriptors[1]); VerifyServiceDescriptor <Delta, Delta>(ServiceLifetime.Scoped, serviceDescriptors[2]); VerifyServiceDescriptor <IGamma, Gamma>(ServiceLifetime.Scoped, serviceDescriptors[3]); }
public GenerationStartupServiceConfig(IEnumerable <IGenerationStartup> startups, IReadOnlyCollection <ServiceDescriptor> sourceCollection, IServiceProvider sourceProvider) { // Configure service provider foreach startup StartupServices = startups.ToDictionary(startup => startup, startup => { // Maybe we can make this lazy initialized // We include all services provided by the generator to each startup var services = new ServiceCollection(); foreach (var service in sourceCollection) { services.Add(new ServiceDescriptor(service.ServiceType, provider => { if (service.Lifetime == ServiceLifetime.Singleton) { return(sourceProvider.GetService(service.ServiceType)); } var sourceService = provider.GetRequiredService <SourceScopeService>().CurrentScopeService; return(sourceService.GetService(service.ServiceType)); }, service.Lifetime)); } services.AddSingleton <SourceScopeService>(); services.AddTypeComposite(); services.AddFeatureProvider(startup); services.AddSourceValidation(); // Add ISourceValidation for each startup return(services.BuildServiceProvider() as IServiceProvider); }); }
public void AddDynamicProxyWithImplementationFactoryAndOptionsForInterfaceResolution() { var services = new ServiceCollection(); TestService ImplementationFactory(IServiceProvider sp) => new TestService(); var proxyGenerationOptions = new ProxyGenerationOptions(); IInterceptor[] interceptors = { new StandardInterceptor() }; services.Add <ITestService, TestService>( ImplementationFactory, ServiceLifetime.Transient, proxyGenerationOptions, interceptors); var serviceProvider = services.BuildServiceProvider(); var service = serviceProvider.GetService <ITestService>(); Assert.IsNotNull(service); Assert.IsInstanceOf <ITestService>(service); var proxyTargetAccessor = service as IProxyTargetAccessor; Assert.IsNotNull(proxyTargetAccessor); var actualInterceptors = proxyTargetAccessor.GetInterceptors(); Assert.AreEqual(actualInterceptors.Length, interceptors.Length); Assert.AreEqual(actualInterceptors[0], interceptors[0]); var proxyTarget = proxyTargetAccessor.DynProxyGetTarget(); Assert.IsInstanceOf <TestService>(proxyTarget); }
public void AddDynamicProxyWithoutOptionsForClassResolution() { var services = new ServiceCollection(); IInterceptor[] interceptors = { new StandardInterceptor() }; services.Add <TestService>( ServiceLifetime.Transient, interceptors); var serviceProvider = services.BuildServiceProvider(); var service = serviceProvider.GetService <TestService>(); Assert.IsNotNull(service); Assert.IsInstanceOf <TestService>(service); var proxyTargetAccessor = service as IProxyTargetAccessor; Assert.IsNotNull(proxyTargetAccessor); var actualInterceptors = proxyTargetAccessor.GetInterceptors(); Assert.AreEqual(actualInterceptors.Length, interceptors.Length); Assert.AreEqual(actualInterceptors[0], interceptors[0]); var proxyTarget = proxyTargetAccessor.DynProxyGetTarget(); Assert.IsInstanceOf <TestService>(proxyTarget); }
private void Instance_AuthorizationRegistredEvent(UserModel userModel, UserSettingsModel userSettingsModel) { if (ServiceExists(userModel.UserId.ToString())) { return; } var token = new TokenResponse { RefreshToken = userModel.RefreshToken, AccessToken = userModel.AccessToken, ExpiresInSeconds = userModel.ExpiresIn, TokenType = userModel.TokenType, IssuedUtc = userModel.IssuedTimeUtc }; var credentials = new BotUserCredential(new GoogleAuthorizationCodeFlow( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = _clientSecrets, Scopes = UserAccessAttribute.GetScopesValue(userSettingsModel.Access), DataStore = new DbDataStore() }), userModel, token); var serviceInitializer = new BaseClientService.Initializer { ApiKey = BotInitializer.Instance.BotSettings.GmnbApiKey, ApplicationName = BotInitializer.Instance.BotSettings.ApplicationName, HttpClientInitializer = credentials }; ServiceCollection.Add(new Service(credentials, serviceInitializer, userSettingsModel.Access)); }
public void HostingEngineCanBeStarted() { var serviceCollection = new ServiceCollection(); serviceCollection.Add(HostingServices.GetDefaultServices()); var services = serviceCollection.BuildServiceProvider(); var engine = services.GetRequiredService <IHostingEngine>(); var context = new HostingContext { ServerFactory = this, Services = services, ApplicationName = "Microsoft.AspNet.Hosting.Tests" }; var engineStart = engine.Start(context); Assert.NotNull(engineStart); Assert.Equal(1, _startInstances.Count); Assert.Equal(0, _startInstances[0].DisposeCalls); engineStart.Dispose(); Assert.Equal(1, _startInstances[0].DisposeCalls); }
public virtual void ConfigureServices(IServiceCollection services) { // Create a temporary copy of base services var tmpServices = new ServiceCollection(); foreach (var serviceDescriptor in services) { tmpServices.Add(serviceDescriptor); } // Add modules as transient services to the temporary container to be able to instantiate them // They will be able to use services, configured using the StageZero modules foreach (var moduleType in this.modules) { tmpServices.AddTransient(moduleType); } var tmpContainer = tmpServices.BuildServiceProvider(); // Configure main app service container using modules from the temporary container foreach (var moduleType in this.modules) { var module = (IAppModule)tmpContainer.GetService(moduleType); module.ConfigureServices(services); } }
private static void SingletonAndTransient() { Console.WriteLine(nameof(SingletonAndTransient)); ServiceProvider RegisterServices() { IServiceCollection services = new ServiceCollection(); services.AddSingleton <IServiceA, ServiceA>(); services.AddTransient <IServiceB, ServiceB>(); // services.AddSingleton<ControllerX>(); services.Add(new ServiceDescriptor(typeof(ControllerX), typeof(ControllerX), ServiceLifetime.Transient)); services.AddSingleton <INumberService, NumberService>(); return(services.BuildServiceProvider()); } using (ServiceProvider container = RegisterServices()) { Console.WriteLine($"requesting {nameof(ControllerX)}"); ControllerX x = container.GetRequiredService <ControllerX>(); x.M(); x.M(); Console.WriteLine($"requesting {nameof(ControllerX)}"); ControllerX x2 = container.GetRequiredService <ControllerX>(); x2.M(); Console.WriteLine(); } }
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); }
public void InjectingProviderInjects() { const string keyVaultVarName = "$$KeyVaultVar$$"; const string propertyPrefix = "Value "; const string propertyValue = propertyPrefix + keyVaultVarName; const string keyVaultVarValue = "KeyVaultVar-123"; const string properyInjectedValue = propertyPrefix + keyVaultVarValue; var injectorMock = new Mock <ISecretInjector>(); injectorMock .Setup(injector => injector.InjectAsync(propertyValue)) .ReturnsAsync(properyInjectedValue); var configurationBuilder = new ConfigurationBuilder() .Add(new InjectedTestConfigurationSource(propertyValue, injectorMock.Object)); var configurationRoot = configurationBuilder.Build(); var services = new ServiceCollection(); services.Add(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot <>), typeof(NonCachingOptionsSnapshot <>))); services.Configure <TestConfiguration>(configurationRoot); var serviceProvider = CreateServiceProvider(services); var testConfiguration = serviceProvider.GetRequiredService <IOptionsSnapshot <TestConfiguration> >(); Assert.Equal(properyInjectedValue, testConfiguration.Value.Property); }
public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); // Register a mock implementation of each service, AddMvcServices should add another implemenetation. foreach (var serviceType in MutliRegistrationServiceTypes) { var mockType = typeof(Mock<>).MakeGenericType(serviceType.Key); services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType)); } // Act MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services); // Assert foreach (var serviceType in MutliRegistrationServiceTypes) { AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1); foreach (var implementationType in serviceType.Value) { AssertContainsSingle(services, serviceType.Key, implementationType); } } }
private static IServiceCollection CreateServiceCollection(IConfiguration config) { var collection = new ServiceCollection(config); collection.Add(GetDefaultServices(config)); return(collection); }
public void Main(string[] args) { var config = new Configuration(); if (File.Exists(HostingIniFile)) { config.AddIniFile(HostingIniFile); } config.AddEnvironmentVariables(); config.AddCommandLine(args); var serviceCollection = new ServiceCollection(); serviceCollection.Add(HostingServices.GetDefaultServices(config)); var services = serviceCollection.BuildServiceProvider(_serviceProvider); var appEnvironment = _serviceProvider.GetService <IApplicationEnvironment>(); var context = new HostingContext() { Services = services, Configuration = config, ServerName = config.Get("server"), // TODO: Key names ApplicationName = config.Get("app") // TODO: Key names ?? appEnvironment.ApplicationName, EnvironmentName = config.Get("env") ?? "Development" }; var engine = services.GetService <IHostingEngine>(); if (engine == null) { throw new Exception("TODO: IHostingEngine service not available exception"); } var appShutdownService = _serviceProvider.GetService <IApplicationShutdown>(); if (appShutdownService == null) { throw new Exception("TODO: IApplicationShutdown service not available"); } var shutdownHandle = new ManualResetEvent(false); var serverShutdown = engine.Start(context); appShutdownService.ShutdownRequested.Register(() => { serverShutdown.Dispose(); shutdownHandle.Set(); }); var ignored = Task.Run(() => { Console.WriteLine("Started"); Console.ReadLine(); appShutdownService.RequestShutdown(); }); shutdownHandle.WaitOne(); }
public void NonCachingOptionsSnapshotPreventsCaching() { const string propertyValue = "Value"; var configurationRoot = CreateConfigurationRoot(propertyValue); var services = new ServiceCollection(); services.Add(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot <>), typeof(NonCachingOptionsSnapshot <>))); services.Configure <TestConfiguration>(configurationRoot); var serviceProvider = CreateServiceProvider(services); var testConfiguration = serviceProvider.GetRequiredService <IOptionsSnapshot <TestConfiguration> >(); Assert.NotNull(testConfiguration); Assert.Equal(propertyValue, testConfiguration.Value.Property); var testConfiguration2 = serviceProvider.GetRequiredService <IOptionsSnapshot <TestConfiguration> >(); Assert.Same(testConfiguration, testConfiguration2); using (var scope = serviceProvider.CreateScope()) { var scopedInstance = scope.ServiceProvider.GetRequiredService <IOptionsSnapshot <TestConfiguration> >(); Assert.NotSame(scopedInstance, testConfiguration); Assert.NotNull(scopedInstance.Value); Assert.NotSame(scopedInstance.Value, testConfiguration.Value); } }
public static void AddNotificationHandlers(this IServiceCollection services, Type processManagerNotificationHandlerImplementationType) { if (!processManagerNotificationHandlerImplementationType.IsGenericType || processManagerNotificationHandlerImplementationType.GetGenericTypeDefinition().GetGenericArguments().Length != 3) { throw new Exception("Invalid definition handler"); } services.Remove(services.FirstOrDefault(x => x.ImplementationType == processManagerNotificationHandlerImplementationType)); var tempServiceCollection = new ServiceCollection(); foreach (var serviceDesc in services) { tempServiceCollection.Add(serviceDesc); } var sp = tempServiceCollection.BuildServiceProvider(); var defs = sp.GetRequiredService <IEnumerable <IDefinition> >(); foreach (var def in defs) { var dataType = def.GetType().BaseType?.GenericTypeArguments.FirstOrDefault(); if (dataType == null) { throw new Exception("Cannot determine process manager definition data type"); } foreach (var eventType in def.GetEventTypes()) { services.AddScoped(typeof(INotificationHandler <>).MakeGenericType(eventType), processManagerNotificationHandlerImplementationType.MakeGenericType(def.GetType(), dataType, eventType)); } } }
public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); services.AddSingleton <IHostingEnvironment>(GetHostingEnvironment()); // Register a mock implementation of each service, AddMvcServices should add another implementation. foreach (var serviceType in MutliRegistrationServiceTypes) { var mockType = typeof(Mock <>).MakeGenericType(serviceType.Key); services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType)); } // Act services.AddMvc(); // Assert foreach (var serviceType in MutliRegistrationServiceTypes) { AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1); foreach (var implementationType in serviceType.Value) { AssertContainsSingle(services, serviceType.Key, implementationType); } } }
public void ExpandViewLocations_SpecificPlugin( string pluginName, bool exists, IEnumerable<string> viewLocations, IEnumerable<string> expectedViewLocations) { var pluginManagerMock = new Mock<IPluginManager>(); if(exists) pluginManagerMock.Setup(pm => pm[It.IsAny<TypeInfo>()]) .Returns(new PluginInfo(new ModuleStub { UrlPrefix = pluginName }, null, null, null));; var services = new ServiceCollection(); services.Add(new ServiceDescriptor(typeof(IPluginManager), pluginManagerMock.Object)); var target = new PluginViewLocationExtender(); var actionContext = new ActionContext { HttpContext = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() } }; actionContext.ActionDescriptor = new ControllerActionDescriptor { ControllerTypeInfo = typeof(object).GetTypeInfo() }; var context = new ViewLocationExpanderContext( actionContext, "testView", "test-controller", "", false); var result = target.ExpandViewLocations(context, viewLocations); Assert.Equal(expectedViewLocations, result); }
public Student LoadStudentByOsId(string osId = "F17026") { Task <List <Student> > task = new Task <List <Student> >(() => { string request = "student/getStudentInfo?" + "zobrazovatSimsUdaje=true&" + "lang=en&outputFormat=json&" + "osCislo=" + osId + "&" + "rok=2017"; var result = Client.SendRequest(request); if (result != "" && result != "[null]") { result = result.Substring(1, result.Length - 2); var student = JsonConvert.DeserializeObject <Student>(result); if (!ServiceCollection.Contains(student)) { ServiceCollection.Add(student); } return(new List <Student>() { student }); } throw new ServiceException("No student found with specified OsId:[" + osId + "]"); }); AddWork(task); return(ResultHandler(task).First()); }
/// <summary> /// Creates a child container. /// </summary> /// <param name="serviceProvider">The service provider to create a child container for.</param> /// <param name="serviceCollection">The services to clone.</param> public static IServiceCollection CreateChildContainer(this IServiceProvider serviceProvider, IServiceCollection serviceCollection) { IServiceCollection clonedCollection = new ServiceCollection(); foreach (var service in serviceCollection) { // Register the singleton instances to all containers if (service.Lifetime == ServiceLifetime.Singleton) { var serviceTypeInfo = service.ServiceType.GetTypeInfo(); // Treat open-generic registrations differently if (serviceTypeInfo.IsGenericType && serviceTypeInfo.GenericTypeArguments.Length == 0) { // There is no Func based way to register an open-generic type, instead of // tenantServiceCollection.AddSingleton(typeof(IEnumerable<>), typeof(List<>)); // Right now, we regsiter them as singleton per cloned scope even though it's wrong // but in the actual examples it won't matter. clonedCollection.AddSingleton(service.ServiceType, service.ImplementationType); } else { // When a service from the main container is resolved, just add its instance to the container. // It will be shared by all tenant service providers. clonedCollection.AddInstance(service.ServiceType, serviceProvider.GetService(service.ServiceType)); } } else { clonedCollection.Add(service); } } return clonedCollection; }
public Task <int> Main(string[] args) { //Add command line configuration source to read command line parameters. var config = new Configuration(); config.AddCommandLine(args); var serviceCollection = new ServiceCollection(); serviceCollection.Add(HostingServices.GetDefaultServices(config)); var services = serviceCollection.BuildServiceProvider(_hostServiceProvider); var context = new HostingContext() { Services = services, Configuration = config, ServerName = "Microsoft.AspNet.Server.WebListener", ApplicationName = "BugTracker" }; var engine = services.GetService <IHostingEngine>(); if (engine == null) { throw new Exception("TODO: IHostingEngine service not available exception"); } using (engine.Start(context)) { Console.WriteLine("Started the server.."); Console.WriteLine("Press any key to stop the server"); Console.ReadLine(); } return(Task.FromResult(0)); }
// We are not testing singleton here because singleton resolutions always got through // runtime resolver and there is no sense to eliminating call from there public void BuildExpressionElidesDisposableCaptureForEnumerableServices(ServiceLifetime lifetime) { IServiceCollection descriptors = new ServiceCollection(); descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceA), typeof(ServiceA), lifetime)); descriptors.Add(ServiceDescriptor.Describe(typeof(ServiceD), typeof(ServiceD), lifetime)); var disposables = new List <object>(); var provider = new ServiceProvider(descriptors, ServiceProviderOptions.Default); var callSite = provider.CallSiteFactory.GetCallSite(typeof(ServiceD), new CallSiteChain()); var compiledCallSite = CompileCallSite(callSite, provider); var serviceD = (ServiceD)compiledCallSite(provider.Root); Assert.Empty(provider.Root.Disposables); }
private void Setup(ServiceLifetime lifetime) { IServiceCollection services = new ServiceCollection(); for (int i = 0; i < 10; i++) { services.Add(ServiceDescriptor.Describe(typeof(A), typeof(A), lifetime)); } services.Add(ServiceDescriptor.Describe(typeof(B), typeof(B), lifetime)); services.Add(ServiceDescriptor.Describe(typeof(C), typeof(C), lifetime)); _serviceProvider = services.BuildServiceProvider(new ServiceProviderOptions() { Mode = ServiceProviderMode }).CreateScope().ServiceProvider; }
public PenaltyCalculationProcessorServicesTests() { var serviceCollection = new ServiceCollection(); serviceCollection.Add(typeof(IPenaltyCalculationService), typeof(TurkeyPenaltyCalculationService), CountryEnum.TR.GetName(), ServiceLifetime.Transient); serviceCollection.Add(typeof(IPenaltyCalculationService), typeof(UnitedArabEmiratesPenaltyCalculationService), CountryEnum.AE.GetName(), ServiceLifetime.Transient); serviceCollection.AddTransient <IPenaltyCalculationServiceFactoryPatternResolver, PenaltyCalculationServiceFactoryPatternResolver>(); var serviceProvider = serviceCollection.BuildServiceProvider(); factoryPatternResolver = serviceProvider.GetService <IPenaltyCalculationServiceFactoryPatternResolver>(); penaltyCalculationProcessor = new PenaltyCalculationProcessor(factoryPatternResolver); _mockRepo = new MockCountryRepository(); }
public static IServiceProvider ConfigureServices() { var services = new ServiceCollection(); services.Add(new ServiceDescriptor(typeof(IConfiguration), Configuration)); return(services.BuildServiceProvider()); }
static ApplicationBuilder NewApplicationBuilder() { var services = new ServiceCollection(); var testControllers = new TestApplicationPart( typeof(TestsController), typeof(TestsController2), typeof(TestsController3)); services.AddLogging(); services.Add(Singleton <DiagnosticSource>(new DiagnosticListener("test"))); services.Add(Singleton(Options.Create(new MvcOptions()))); services.AddMvcCore().ConfigureApplicationPartManager(m => m.ApplicationParts.Add(testControllers)); services.AddApiVersioning(); services.AddOData().EnableApiVersioning(); return(new ApplicationBuilder(services.BuildServiceProvider())); }
public App() { bool ret; mutex = new System.Threading.Mutex(true, "projecteye", out ret); if (!ret) { //仅允许运行一次进程 //App.Current.Shutdown(); } serviceCollection = new ServiceCollection(); serviceCollection.AddInstance(this); serviceCollection.Add <CacheService>(); serviceCollection.Add <ConfigService>(); serviceCollection.Add <ScreenService>(); serviceCollection.Add <MainService>(); serviceCollection.Add <TrayService>(); serviceCollection.Add <ResetService>(); serviceCollection.Add <SoundService>(); WindowManager.serviceCollection = serviceCollection; serviceCollection.Initialize(); }
public ResourceHandlerTests() { _fhirDataStore = Substitute.For <IFhirDataStore>(); _conformanceProvider = Substitute.For <ConformanceProviderBase>(); _searchService = Substitute.For <ISearchService>(); // TODO: FhirRepository instantiate ResourceDeserializer class directly // which will try to deserialize the raw resource. We should mock it as well. _rawResourceFactory = Substitute.For <RawResourceFactory>(new FhirJsonSerializer()); _resourceWrapperFactory = Substitute.For <IResourceWrapperFactory>(); _resourceWrapperFactory .Create(Arg.Any <ResourceElement>(), Arg.Any <bool>(), Arg.Any <bool>()) .Returns(x => CreateResourceWrapper(x.ArgAt <ResourceElement>(0), x.ArgAt <bool>(1))); _conformanceStatement = CapabilityStatementMock.GetMockedCapabilityStatement(); CapabilityStatementMock.SetupMockResource(_conformanceStatement, ResourceType.Observation, null); var observationResource = _conformanceStatement.Rest.First().Resource.Find(x => x.Type == ResourceType.Observation); observationResource.ReadHistory = false; observationResource.UpdateCreate = true; observationResource.ConditionalCreate = true; observationResource.ConditionalUpdate = true; observationResource.Versioning = CapabilityStatement.ResourceVersionPolicy.Versioned; CapabilityStatementMock.SetupMockResource(_conformanceStatement, ResourceType.Patient, null); var patientResource = _conformanceStatement.Rest.First().Resource.Find(x => x.Type == ResourceType.Patient); patientResource.ReadHistory = true; patientResource.UpdateCreate = true; patientResource.ConditionalCreate = true; patientResource.ConditionalUpdate = true; patientResource.Versioning = CapabilityStatement.ResourceVersionPolicy.VersionedUpdate; _conformanceProvider.GetCapabilityStatementOnStartup().Returns(_conformanceStatement.ToTypedElement().ToResourceElement()); var lazyConformanceProvider = new Lazy <IConformanceProvider>(() => _conformanceProvider); var collection = new ServiceCollection(); // an auth service that allows all. _authorizationService = Substitute.For <IAuthorizationService <DataActions> >(); _authorizationService.CheckAccess(Arg.Any <DataActions>(), Arg.Any <CancellationToken>()).Returns(ci => ci.Arg <DataActions>()); var referenceResolver = new ResourceReferenceResolver(_searchService, new TestQueryStringParser()); _resourceIdProvider = new ResourceIdProvider(); collection.Add(x => _mediator).Singleton().AsSelf(); collection.Add(x => new CreateResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, referenceResolver, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new UpsertResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService, ModelInfoProvider.Instance)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new ConditionalCreateResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _searchService, x.GetService <IMediator>(), _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new ConditionalUpsertResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _searchService, x.GetService <IMediator>(), _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new GetResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new DeleteResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); ServiceProvider provider = collection.BuildServiceProvider(); _mediator = new Mediator(type => provider.GetService(type)); _deserializer = new ResourceDeserializer( (FhirResourceFormat.Json, new Func <string, string, DateTimeOffset, ResourceElement>((str, version, lastUpdated) => _fhirJsonParser.Parse(str).ToResourceElement()))); }
public void AddCustomLocalizers_BeforeAddLocalizationServices_AddsNeededServices() { // Arrange var collection = new ServiceCollection(); // Act collection.Add(ServiceDescriptor.Singleton(typeof(IHtmlLocalizerFactory), typeof(TestHtmlLocalizerFactory))); collection.Add(ServiceDescriptor.Transient(typeof(IHtmlLocalizer <>), typeof(TestHtmlLocalizer <>))); collection.Add(ServiceDescriptor.Transient(typeof(IViewLocalizer), typeof(TestViewLocalizer))); MvcLocalizationServices.AddMvcViewLocalizationServices( collection, LanguageViewLocationExpanderFormat.Suffix); AssertContainsSingle(collection, typeof(IHtmlLocalizerFactory), typeof(TestHtmlLocalizerFactory)); AssertContainsSingle(collection, typeof(IHtmlLocalizer <>), typeof(TestHtmlLocalizer <>)); AssertContainsSingle(collection, typeof(IViewLocalizer), typeof(TestViewLocalizer)); }
public void AddOrReplaceServices(params ServiceDescriptor[] services) { foreach (var service in services) { _serviceCollection.RemoveAll(service.GetType()); _serviceCollection.Add(service); } _serviceProvider = _serviceCollection.BuildServiceProvider(); }
public void DefaultControllerActivatorIsServiceProviderBased() { var collection = new ServiceCollection(); collection.Add(new ServiceDescriptor(typeof(IControllerActivator), new Mock <IControllerActivator>().Object)); var kernel = CreateKernel(collection); kernel.Get <IControllerActivator>().Should().NotBeNull().And.BeOfType(typeof(ServiceBasedControllerActivator)); }
/// <summary> /// Adds dependencies of existing servicecollection to the dependencies list /// </summary> public virtual MicroserviceHostBuilder RegisterDependencies(IServiceCollection serviceCollection) { Logger.LogDebug("Adding registered dependencies from provided collection"); foreach (ServiceDescriptor serviceDescriptor in serviceCollection) { ServiceCollection.Add(serviceDescriptor); } return(this); }
// Need full wrap for generics like IOptions public WrappingServiceProvider(IServiceProvider fallback, IServiceCollection replacedServices) { var services = new ServiceCollection(); var manifest = fallback.GetRequiredService<IRuntimeServices>(); foreach (var service in manifest.Services) { services.AddTransient(service, sp => fallback.GetService(service)); } services.Add(replacedServices); _services = services.BuildServiceProvider(); }
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 SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes() { // Arrange var services = new ServiceCollection(); // Register a mock implementation of each service, AddMvcServices should not replace it. foreach (var serviceType in SingleRegistrationServiceTypes) { var mockType = typeof(Mock<>).MakeGenericType(serviceType); services.Add(ServiceDescriptor.Transient(serviceType, mockType)); } // Act MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services); // Assert foreach (var singleRegistrationType in SingleRegistrationServiceTypes) { AssertServiceCountEquals(services, singleRegistrationType, 1); } }
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 TryAdd_WithType_DoesNotAddDuplicate( Action<IServiceCollection> addAction, Type expectedServiceType, Type expectedImplementationType, ServiceLifetime expectedLifetime) { // Arrange var collection = new ServiceCollection(); collection.Add(ServiceDescriptor.Transient(expectedServiceType, expectedServiceType)); // Act addAction(collection); // Assert var descriptor = Assert.Single(collection); Assert.Equal(expectedServiceType, descriptor.ServiceType); Assert.Same(expectedServiceType, descriptor.ImplementationType); Assert.Equal(ServiceLifetime.Transient, descriptor.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 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); }
/// <summary> /// Register the needed services /// </summary> /// <param name="services"></param> /// <param name="project"></param> private static void RegisterNeededServices(ServiceCollection services, IProject project) { ServiceCollection rootServices = ApplicationContext.Current.RootWorkItem.Services; rootServices.Add<IProjectContextService>(new SimpleProjectContextService(project)); rootServices.AddNew<ProjectLocalizationService>(); rootServices.Add<IPortalDeploymentService>(new PortalDeploymentService()); ITypeResolutionService resService = new TypeResolutionService(); services.Add(typeof(ITypeResolutionService), resService); services.Add(typeof(ITypeDiscoveryService), resService); }
private static void Main(string[] args) { SetupConsole(); try { var config = new FilterConfig("Config\\Filter.xml"); //Logger foreach (var logger in config.Logger) { StaticLogger.Create(logger.Key); StaticLogger.SetLogLevel(logger.Value.Ordinal, logger.Key); } StaticLogger.SetInstance(); //StaticLogger.Instance.Trace("Trace"); //StaticLogger.Instance.Debug("Debug"); //StaticLogger.Instance.Info("Info"); //StaticLogger.Instance.Warn("Warn"); //StaticLogger.Instance.Error("Error"); //StaticLogger.Instance.Fatal("Fatal"); //Services _serviceCollection = new ServiceCollection(); foreach (var serviceSettings in config.Services) { var service = new Service(serviceSettings.Value); _serviceCollection.Add(service); } //Plugins var pluginManager = new PluginManager(config.Plugins); foreach (var service in _serviceCollection) { pluginManager.RegisterService(service); } var pluginCount = pluginManager.Load(); StaticLogger.Instance.Info($"{pluginCount} plugins registered."); //Start services foreach (var service in _serviceCollection) { var result = service.Start(); if (result == false) StaticLogger.Instance.Fatal($"Failed to start {service.Settings.Name}, check Filter.xml and prev. errors"); } StaticLogger.Instance.Info("Successfully initilized."); Console.Beep(); while (true) { var line = Console.ReadLine(); if (line == "exit" || line == "quit") break; } foreach (var service in _serviceCollection) { service.Stop(); } } catch (Exception ex) { Console.Beep(); Console.WriteLine("Something f****d up really hard, please check Filter.xml"); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); Console.Beep(); Console.ReadLine(); } }
private static ServiceProvider GetServiceProvider(params ServiceDescriptor[] descriptors) { var collection = new ServiceCollection(); foreach (var descriptor in descriptors) { collection.Add(descriptor); } return (ServiceProvider)collection.BuildServiceProvider(); }