Example #1
0
        static IServiceProvider CreateContainer(IAzureFunctionsApi azureFunctionsApi, IGitHubApiV3 gitHubApiV3, IGitHubGraphQLApi gitHubGraphQLApi)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            //GitTrends Refit Services
            services.AddSingleton(azureFunctionsApi);
            services.AddSingleton(gitHubApiV3);
            services.AddSingleton(gitHubGraphQLApi);

            //GitTrends Services
            services.AddSingleton <AzureFunctionsApiService>();
            services.AddSingleton <BackgroundFetchService>();
            services.AddSingleton <DeepLinkingService>();
            services.AddSingleton <NotificationService, ExtendedNotificationService>();
            services.AddSingleton <GitHubApiV3Service>();
            services.AddSingleton <GitHubApiRepositoriesService>();
            services.AddSingleton <GitHubApiStatusService>();
            services.AddSingleton <GitHubAuthenticationService>();
            services.AddSingleton <GitHubGraphQLApiService>();
            services.AddSingleton <GitHubUserService>();
            services.AddSingleton <GitTrendsContributorsService>();
            services.AddSingleton <FavIconService>();
            services.AddSingleton <FirstRunService>();
            services.AddSingleton <ImageCachingService>();
            services.AddSingleton <LanguageService>();
            services.AddSingleton <MediaElementService>();
            services.AddSingleton <ReferringSitesDatabase>();
            services.AddSingleton <RepositoryDatabase>();
            services.AddSingleton <ReviewService>();
            services.AddSingleton <MobileSortingService>();
            services.AddSingleton <SyncfusionService>();
            services.AddSingleton <ThemeService>();
            services.AddSingleton <TrendsChartSettingsService>();

            //GitTrends ViewModels
            services.AddTransient <OnboardingViewModel>();
            services.AddTransient <ReferringSitesViewModel>();
            services.AddTransient <RepositoryViewModel>();
            services.AddTransient <SettingsViewModel>();
            services.AddTransient <SplashScreenViewModel>();
            services.AddTransient <TrendsViewModel>();
            services.AddTransient <WelcomeViewModel>();

            //Mocks
            services.AddSingleton <IAnalyticsService, MockAnalyticsService>();
            services.AddSingleton <IAppInfo, MockAppInfo>();
            services.AddSingleton <IBrowser, MockBrowser>();
            services.AddSingleton <IDeviceNotificationsService, MockDeviceNotificationsService>();
            services.AddSingleton <IFileSystem, MockFileSystem>();
            services.AddSingleton <IEmail, MockEmail>();
            services.AddSingleton <ILauncher, MockLauncher>();
            services.AddSingleton <IMainThread, MockMainThread>();
            services.AddSingleton <INotificationManager, MockNotificationManager>();
            services.AddSingleton <ISecureStorage, MockSecureStorage>();
            services.AddSingleton <IPreferences, MockPreferences>();
            services.AddSingleton <IVersionTracking, MockVersionTracking>();

            return(services.BuildServiceProvider());
        }
Example #2
0
        public void AddPollyPolicy_ShouldRegisterCircuitBreakerManagerAsSingleton()
        {
            var serviceCollection = new ServiceCollectionImpl();

            serviceCollection.AddPollyPolicy("Test", GetCircuitBreakerPolicy());

            AssertManagerRegistered(serviceCollection);
        }
            public ServiceCollection()
            {
                var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

                services.AddServiceResolution();

                _sut = services.BuildServiceProvider().GetRequiredService <ServiceFactory>();
            }
Example #4
0
        public static void Configure(IConfiguration configuration)
        {
            IServiceCollection serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));
            serviceCollection.AddLogging(builder => builder.AddDynamicConsole());
            LoggerFactory = serviceCollection.BuildServiceProvider().GetService <ILoggerFactory>();
        }
Example #5
0
        private static void Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                if (o.Verbose)
                {
                    Log.Logger = new LoggerConfiguration()
                                 .MinimumLevel.Verbose()
                                 .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                                 .WriteTo.File("log.log", rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                                 .CreateLogger();
                    Log.Information("Application started.");
                    Log.Verbose("Verbose output enabled.");
                }
                else
                {
                    Log.Logger = new LoggerConfiguration()
                                 .MinimumLevel.Information()
                                 .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                                 .WriteTo.File("log.log", rollingInterval: RollingInterval.Day, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                                 .CreateLogger();
                    Log.Information("Application started.");
                    Log.Information("Error output enabled.");
                }
                Log.Information($"Application Start: {DateTime.Now}");

                if (!Directory.Exists(o.Source))
                {
                    var m = $"Source directory \"{o.Source}\" does not exist!";
                    Log.Error(m);
                    throw new Exception(m);
                }

                if (!Directory.Exists(o.Destination))
                {
                    var m = $"Destination directory \"{o.Destination}\" does not exist!";
                    Log.Error(m);
                    throw new Exception(m);
                }


                //setup our DI
                var serviceProvider = new Microsoft.Extensions.DependencyInjection.ServiceCollection()
                                      .AddLogging()
                                      .AddSingleton <IWatermarkService, WatermarkService>()
                                      .BuildServiceProvider();


                //do the actual work here
                var bar = serviceProvider.GetService <IWatermarkService>();
                bar.DoThing(5);

                Log.Information($"Application Finished: {DateTime.Now}");
            });
        }
Example #6
0
        public void Configuration(IAppBuilder app)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            ConfigureAuth(app);
            ConfigureServices(services);
            var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());

            DependencyResolver.SetResolver(resolver);
        }
Example #7
0
        public static IAuthorizationService BuildAuthorizationService(Action <IServiceCollection> setupServices = null)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddAuthorization();
            services.AddOptions();
            services.AddLogging();
            setupServices?.Invoke(services);
            return(services.BuildServiceProvider().GetRequiredService <IAuthorizationService>());
        }
Example #8
0
        public void Medaitor_1AddLatransMedaitor()
        {
            var servicesWebApp = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var b = servicesWebApp.AddLatransMedaitor();

            //b.Build();
            Assert.Contains(servicesWebApp, sd => typeof(IMediatorClientFactory) == sd.ServiceType);
            Assert.Contains(servicesWebApp, sd => typeof(IMediatorClient) == sd.ServiceType);
            Assert.Contains(servicesWebApp, sd => typeof(IMediatorService) == sd.ServiceType);
        }
Example #9
0
        public void AddPollyPolicies_ShouldRegisterCircuitBreakerManagerAsSingleton()
        {
            var serviceCollection = new ServiceCollectionImpl();
            var dict = new Dictionary <string, ICircuitBreakerPolicy> {
                { "Test", GetCircuitBreakerPolicy() }
            };

            serviceCollection.AddPollyPolicies(dict);

            AssertManagerRegistered(serviceCollection);
        }
Example #10
0
        public static async Task Main(string[] args)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            ConfigureServices(services);

            var provider = services.BuildServiceProvider();

            var app = provider.GetService <Application>();
            await app.Verify("password1");
        }
Example #11
0
        public void ShouldLoadSomeServicesFromExecutingAssembly_CheckRegistrationByImplementation_LoadByAssembly()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddAutoRegister(Assembly.GetAssembly(typeof(ServiceCollectionProviderTests)));
            var provider       = services.BuildServiceProvider();
            var resolveService = provider.GetService <FirstClass>();

            Assert.NotNull(resolveService);
            Assert.IsType <FirstClass>(resolveService);
        }
        Clone(Microsoft.Extensions.DependencyInjection.IServiceCollection serviceCollection)
        {
            Microsoft.Extensions.DependencyInjection.IServiceCollection clone =
                new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            foreach (Microsoft.Extensions.DependencyInjection.ServiceDescriptor service in serviceCollection)
            {
                clone.Add(service);
            }

            return(clone);
        }
Example #13
0
        public void ConcretionClassWithMultipleConstructorsIsRegisteredCorrectly()
        {
            // arrange
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var sut = new ContainerSetup(serviceCollection);
            var act = new Action(() => sut.RetrieveConcretionClassesRequiringRegistration(true));

            // act
            // assert
            act.Should().NotThrow <Exception>();
        }
Example #14
0
        public void GetRequiredService_NotRegistered_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var serviceProvider   = serviceCollection.BuildServiceProvider();

            Func <TestServiceTwoParams <string, double> > factory = () => serviceProvider.GetRequiredService <TestServiceTwoParams <string, double> >();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"No service for type '{typeof(TestServiceTwoParams<string, double>)}' has been registered.");
        }
Example #15
0
        public void Medaitor_2AddHandler()
        {
            var servicesWebApp   = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var servicesMediator = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var b = servicesWebApp.AddLatransMedaitor();

            b.AddActivityHandler <TestActivityHandler1>()
            .Build();

            Assert.Contains(b.Services, sd => typeof(IActivityHandler <TestRequest1, TestResponse1>) == sd.ServiceType);
        }
Example #16
0
        public void ShouldLoadSomeServicesFromExecutingAssembly_CheckRegistrationByServiceType_LoadByType()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddAutoRegister(typeof(ServiceCollectionProviderTests));
            var provider       = services.BuildServiceProvider();
            var resolveService = provider.GetService <ISecondClass>();

            Assert.NotNull(resolveService);
            Assert.IsAssignableFrom <ISecondClass>(resolveService);
        }
Example #17
0
        public SampleExamContext CreateDbContext()
        {
            var config           = new ConfigurationBuilder().AddEnvironmentVariables().Build();
            var services         = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var connectionString = config.GetValue <string>(IntegrationTestConstants.CONN_STRING_KEY_TEST);

            services.AddDbContext <SampleExam.Infrastructure.Data.SampleExamContext>(opt => opt.UseNpgsql(connectionString));
            var serviceProvider = services.BuildServiceProvider();
            var dbContext       = serviceProvider.GetRequiredService <SampleExamContext>();

            return(dbContext);
        }
Example #18
0
        public async Task InvokeCall_succeeds()
        {
            var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();
            var mockHttpRequest         = new Mock <HttpRequest>();

            mockHttpRequest.Setup(_ => _.Headers)
            .Returns(new HeaderDictionary {
                { "tenantId", "1" }
            });
            mockHttpContextAccessor.Setup(x => x.HttpContext.Request)
            .Returns(mockHttpRequest.Object);

            //setup serviceCollection
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            foreach (var tenant in _tenants)
            {
                if (tenant.Id == 1)
                {
                    serviceCollection.AddTenantScoped(tenant, typeof(IFooService), typeof(DefaultFooService), ServiceLifetime.Scoped);
                }
                else
                {
                    serviceCollection.AddTenantScoped(tenant, typeof(IFooService), typeof(SpecialFooService), ServiceLifetime.Scoped);
                }

                //this singleton is tenant scoped.
                //there will be a singleton for each tenant
                serviceCollection.AddTenantScoped(tenant, typeof(IBarService), typeof(BarService), ServiceLifetime.Singleton);
            }

            serviceCollection.AddSingleton(_ => mockHttpContextAccessor);
            serviceCollection.AddSingleton <ITenantProvider, MockTenantProvider>();
            serviceCollection.AddSingleton <ITenantResolutionStrategy, HeaderTenantResolutionStrategy>();
            serviceCollection.AddSingleton <IBazService, BazService>();
            serviceCollection.AddSingleton(mockHttpContextAccessor.Object);

            mockHttpContextAccessor.Setup(x => x.HttpContext.RequestServices)
            .Returns(serviceCollection.BuildServiceProvider());

            string foo = null;
            var    sut = new TenantMiddleware(next: (innerHttpContext) =>
            {
                //do something in next request delegate
                foo = "executed";
                return(Task.CompletedTask);
            },
                                              new ContainerBuilder(_tenants, serviceCollection));

            await sut.Invoke(mockHttpContextAccessor.Object.HttpContext);

            Assert.Equal("executed", foo);
        }
Example #19
0
        public async Task TenantSpecificServices_ShouldBeInjected()
        {
            //setup IHttpContextAccessor
            var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();
            var mockHttpRequest         = new Mock <HttpRequest>();

            mockHttpRequest.Setup(_ => _.Headers)
            .Returns(new HeaderDictionary {
                { "tenantId", "2" }
            });
            mockHttpContextAccessor.Setup(x => x.HttpContext.Request)
            .Returns(mockHttpRequest.Object);

            //setup serviceCollection
            var masterServiceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            foreach (var tenant in _tenants)
            {
                if (tenant.Id == 1)
                {
                    masterServiceCollection.AddTenantScoped(tenant, typeof(IFooService), typeof(SpecialFooService), ServiceLifetime.Scoped);
                }
                else
                {
                    masterServiceCollection.AddTenantScoped(tenant, typeof(IFooService), typeof(DefaultFooService), ServiceLifetime.Scoped);
                }

                //this singleton is tenant scoped.
                //there will be a singleton for each tenant
                masterServiceCollection.AddTenantScoped(tenant, typeof(IBarService), typeof(BarService), ServiceLifetime.Singleton);
            }

            masterServiceCollection.AddSingleton <ITenantProvider, MockTenantProvider>();
            masterServiceCollection.AddSingleton <ITenantResolutionStrategy, HeaderTenantResolutionStrategy>();
            masterServiceCollection.AddSingleton <IBazService, BazService>();
            masterServiceCollection.AddSingleton(mockHttpContextAccessor.Object);

            mockHttpContextAccessor.Setup(x => x.HttpContext.RequestServices)
            .Returns(masterServiceCollection.BuildServiceProvider());

            var sut = new TenantMiddleware(next: (innerHttpContext) =>
            {
                var fooService = innerHttpContext.RequestServices.GetService <IFooService>();
                Assert.NotNull(fooService);
                Assert.IsType <DefaultFooService>(fooService);

                return(Task.CompletedTask);
            },
                                           new ContainerBuilder(_tenants, masterServiceCollection));

            await sut.Invoke(mockHttpContextAccessor.Object.HttpContext);
        }
Example #20
0
        public void GetRequiredService_FactoryOfOneArgForInterfaceOfRegisteredType_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceOneParam <string> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <string, ITestInterfaceOneParam <string> > > factory = () => serviceProvider.GetRequiredService <IFactory <string, ITestInterfaceOneParam <string> > >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"Unable to resolve service for type '{typeof(ITestInterfaceOneParam<string>)}' while attempting to activate '{typeof(IFactory<string, ITestInterfaceOneParam<string>>)}'.");
        }
Example #21
0
        public void New_FactoryOfOneArgForRegisteredInterface_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <ITestInterfaceOneParam <string>, TestServiceOneParam <string> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string, ITestInterfaceOneParam <string> > >();

            factory.New("a").Arg.Should().Be("a");
            factory.New("b").Arg.Should().Be("b");
        }
Example #22
0
        public void GetRequiredService_FactoryOfOneArgForTypeWithTwoMatchingConstructors_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <int, TwoConstructors> > factory = () => serviceProvider.GetRequiredService <IFactory <int, TwoConstructors> >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"In order to resolve a parameterised factory for service type '{typeof(TwoConstructors)}', the implementation type '{typeof(TwoConstructors)}' must contain just one constructor whose last parameter is assignable from the factory argument type '{typeof(int)}'.");
        }
Example #23
0
        public void GetRequiredService_TwoConstructorsServicesRegisteredForNeither_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <TwoConstructors> factory = () => serviceProvider.GetRequiredService <TwoConstructors>();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"No constructor for type '{typeof(TwoConstructors)}' can be instantiated using services from the service container and default values.");
        }
Example #24
0
        public void GetRequiredService_FactoryOfOneArgForTypeRegisteredAsNonTransient_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddScoped <TestServiceOneParam <string> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <string, TestServiceOneParam <string> > > factory = () => serviceProvider.GetRequiredService <IFactory <string, TestServiceOneParam <string> > >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"In order to resolve a parameterised factory for service type '{typeof(TestServiceOneParam<string>)}', the implementation type '{typeof(TestServiceOneParam<string>)}' must be registered with Transient lifestyle.");
        }
Example #25
0
        public void RequestExecutionService_2_Test()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddRequestPipe();
            using (var serviceProviderRoot = services.BuildServiceProvider()) {
                using (var scope = serviceProviderRoot.CreateScope()) {
                    var serviceProviderScope = scope.ServiceProvider;
                    var sut = serviceProviderScope.GetRequiredService <IRequestExecutionService>();
                    Assert.NotNull(sut);
                }
            }
        }
Example #26
0
        public void New_FactoryOfOneArgOfAssignableType_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceOneParam <IEnumerable <string> > >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string[], TestServiceOneParam <IEnumerable <string> > > >();

            factory.New(new[] { "a" }).Arg.Single().Should().Be("a");
            factory.New(new[] { "b" }).Arg.Single().Should().Be("b");
        }
Example #27
0
        public static async Task Main(string[] args)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            ConfigureServices(services);

            var provider = services.BuildServiceProvider();

            var app = provider.GetService <Application>();
            await app.StartPhoneVerificationAsync("1", "5551234567");

            // await app.CheckPhoneVerificationAsync("1", "5551234567", "6494");
        }
Example #28
0
        public void GetRequiredService_FactoryOfTwoArgsForTypeWithWrongConstructor_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <WrongConstructor>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <string, double, WrongConstructor> > factory = () => serviceProvider.GetRequiredService <IFactory <string, double, WrongConstructor> >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"In order to resolve a parameterised factory for service type '{typeof(WrongConstructor)}', the implementation type '{typeof(WrongConstructor)}' must contain a constructor whose last 2 parameters are assignable from the factory argument types '{typeof(string)}', '{typeof(double)}'.");
        }
        public static ServiceProvider CreateServiceProvider(Action <IServiceCollection> addServices)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddLogging((loggingBuilder) => {
                loggingBuilder.AddDebug();
            });
            if (addServices != null)
            {
                addServices(services);
            }
            return(services.BuildServiceProvider(true));
        }
Example #30
0
        private IServiceCollection SetupRegisteredManager(string policyName = null)
        {
            var serviceCollection = new ServiceCollectionImpl();
            var manager           = new CircuitBreakerManager();

            if (!string.IsNullOrEmpty(policyName))
            {
                manager.TryAdd(policyName, GetCircuitBreakerPolicy());
            }
            serviceCollection.AddSingleton <ICircuitBreakerManager>(manager);

            return(serviceCollection);
        }