Esempio n. 1
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);
                }
            }
        }
Esempio n. 2
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");
        }
Esempio n. 3
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.");
        }
        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));
        }
        private void BeforeAllTests()
        {
            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();

            this.dbContext = serviceProvider.GetRequiredService <SampleExamContext>();
            dbContext.Database.EnsureDeleted();
            dbContext.Database.EnsureCreated();
            SampleExamContextHelper.SeedContext(dbContext);
        }
Esempio n. 6
0
        static IServiceProvider CreateContainer()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            //GitTrends Services
            services.AddSingleton <AzureFunctionsApiService>();
            services.AddSingleton <BackgroundFetchService>();
            services.AddSingleton <DeepLinkingService>();
            services.AddSingleton <NotificationService, ExtendedNotificationService>();
            services.AddSingleton <GitHubApiV3Service>();
            services.AddSingleton <GitHubAuthenticationService>();
            services.AddSingleton <GitHubGraphQLApiService>();
            services.AddSingleton <GitHubUserService>();
            services.AddSingleton <FavIconService>();
            services.AddSingleton <FirstRunService>();
            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());
        }
Esempio n. 7
0
        public void GetRequiredService_NestedDependencyNotRegistered_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

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

            Func <TestServiceOneParam <WrongConstructor> > factory = () => serviceProvider.GetRequiredService <TestServiceOneParam <WrongConstructor> >();

            // 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($"Unable to resolve service for type '{typeof(double)}' while attempting to activate '{typeof(WrongConstructor)}'.");
        }
Esempio n. 8
0
        public void RequestExecutionService_1_ArgumentNullException_Test()
        {
            {
                Assert.Throws <ArgumentNullException>(() => {
                    var sut = new RequestExecutionService(new RequestPipeOptions(), (IServiceProvider)null);
                    return(sut);
                });
            }
            {
                Assert.Throws <ArgumentNullException>(() => {
                    var sut = new RequestExecutionService(new RequestPipeOptions(), (IRequestHandlerFactory)null);
                    return(sut);
                });
            }
            {
                var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
                using (var serviceProviderRoot = services.BuildServiceProvider()) {
                    var sut = new RequestExecutionService((RequestPipeOptions)null !, serviceProviderRoot);
                    Assert.NotNull(sut);
                }
            }
            {
                var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
                services.AddRequestPipe();
                using (var serviceProviderRoot = services.BuildServiceProvider()) {
                    var sut = serviceProviderRoot.GetRequiredService <IRequestExecutionService>();
                    Assert.NotNull(sut);

                    Assert.ThrowsAsync <ArgumentNullException>(() => {
                        return(sut.ExecuteAsync <object>(null, CancellationToken.None, null));
                    });
                }
            }
            {
                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);

                        Assert.ThrowsAsync <ArgumentNullException>(() => {
                            return(sut.ExecuteAsync <object>(null, CancellationToken.None, null));
                        });
                    }
                }
            }
        }
Esempio n. 9
0
        private static void Run_UsingUnityDI(string[] args)
        {
            using (var container = new Unity.UnityContainer().EnableDiagnostic())
            {
                string environment = Settings.Environment();
                string notificationRecipientList = Settings.NotificationRecipientList();
                string sendEmailGateway          = Settings.SendEmailGateway();

                //  --  httpclientfactory
                Microsoft.Extensions.DependencyInjection.ServiceCollection serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
                serviceCollection.AddHttpClient("Sender", (c) =>
                {
                    c.BaseAddress = new Uri(sendEmailGateway);
                });
                serviceCollection.BuildServiceProvider(container);
                //var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
                IHttpClientFactory clientFactory = container.Resolve <IHttpClientFactory>();
                HttpClient         httpClient    = clientFactory.CreateClient("Sender");

                container.RegisterSingleton <IConfig, AppConfig>(
                    new InjectionProperty("Environment", environment)
                    , new InjectionProperty("NotificationRecipientList", notificationRecipientList)
                    , new InjectionProperty("SendEmailGateway", sendEmailGateway)
                    );

                container.RegisterSingleton <ILogger, Logger>();


                //Sender(IConfig config, IHttpClientFactory httpClientFactory, ILogger logger)

                /*
                 * container.RegisterSingleton<ISender, Sender>(
                 *  new InjectionConstructor(
                 *             new ResolvedParameter(typeof(IConfig))
                 *             , new ResolvedParameter(typeof(IHttpClientFactory))
                 *             , new ResolvedParameter(typeof(ILogger))
                 *         )
                 *  );*/
                container.RegisterSingleton <ISender, Sender>();

                container.RegisterType(typeof(RemoteAppenderSink));

                var sink = container.Resolve <RemoteAppenderSink>();

                //sink.EventsReached += (s, a) => AddLog(a.LoggingEvents);
                RemotingConfiguration.Configure("log4netListener.exe.config", false);
                RemotingServices.Marshal(sink, "RemoteAppenderLoggingSink");
            }
        }
Esempio n. 10
0
        public void New_FactoryOfTwoArgWithMissingService_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

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

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

            Func <WrongConstructor> instance = () => factory.New("a", 1);

            instance.Should().Throw <InvalidOperationException>()
            .WithMessage($"Unable to resolve service for type '{typeof(double)}' while attempting to activate '{typeof(WrongConstructor)}'.");
        }
Esempio n. 11
0
        public void GetRequiredService_TwoConstructorsServicesRegisteredForOne_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            serviceCollection.AddSingleton(typeof(string), "a");
            serviceCollection.AddSingleton(typeof(int), 1);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            var instance = serviceProvider.GetRequiredService <TwoConstructors>();

            instance.A.Should().Be("a");
            instance.B.Should().Be(1);
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            //build DI Services
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <MainApp>();
            serviceCollection.AddTransient <ISalaryFormula, SalaryFormula>();
            //serviceCollection.AddTransient<ISalaryFormula, BossSalaryFormula>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            //run MainApp.Main with DI
            serviceProvider.GetRequiredService <MainApp>().Main();

            Console.ReadKey();
        }
Esempio n. 13
0
        public void ConcretionClassesCorrectlyApplyReuse()
        {
            // arrange
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var sut = new ContainerSetup(serviceCollection);

            // act
            sut.RetrieveConcretionClassesRequiringRegistration(true);

            // assert
            var services        = serviceCollection.BuildServiceProvider();
            var resolvedClasses = ((IEnumerable <ITestInterfaceDummy>)services.GetService(typeof(IEnumerable <ITestInterfaceDummy>))).ToList();
            var secondResolve   = ((IEnumerable <ITestInterfaceDummy>)services.GetService(typeof(IEnumerable <ITestInterfaceDummy>))).ToList();

            resolvedClasses.Should().BeEquivalentTo(secondResolve);
        }
Esempio n. 14
0
        public void ConcretionClassesAreResolvedCorrectly()
        {
            // arrange
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var sut = new ContainerSetup(serviceCollection);

            // act
            sut.RetrieveConcretionClassesRequiringRegistration(true);

            // assert
            var services      = serviceCollection.BuildServiceProvider();
            var resolvedClass = ((IEnumerable <BaseClassDummy>)services.GetService(typeof(IEnumerable <BaseClassDummy>))).ToList();

            resolvedClass.Count.Should().Be(1);
            resolvedClass.First().GetType().Should().Be(typeof(InheritorClassDummy));
        }
Esempio n. 15
0
        public void TransientRegistrationsAreResolvedCorrectly()
        {
            // arrange
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var sut = new ContainerSetup(serviceCollection);

            // act
            sut.RetrieveClassesRequiringRegistration(true);

            // assert
            var services      = serviceCollection.BuildServiceProvider();
            var resolvedClass = services.GetService <AutoRegistrationDummy>();
            var secondResolve = services.GetService <AutoRegistrationDummy>();

            resolvedClass.Should().NotBe(secondResolve);
        }
Esempio n. 16
0
        public async Task Medaitor_9Monitor()
        {
            var servicesWebApp   = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var servicesMediator = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            servicesWebApp.AddLatransMedaitor()
            .AddActivityHandler <TestActivityHandler5>()
            .Build();

            ActivityId activityId = ActivityId.NewId();

            using (var serviceProviderMediator = servicesMediator.BuildServiceProvider()) {
                using (var serviceProviderWebApp = servicesWebApp.BuildServiceProvider()) {
                    using (var scopeWebApp2 = serviceProviderWebApp.CreateScope()) {
                        var scopedProviderWebApp2 = scopeWebApp2.ServiceProvider;
                        var medaitorClient2       = scopedProviderWebApp2.GetRequiredService <IMediatorClientFactory>().GetMedaitorClient();


                        using (var scopeWebApp1 = serviceProviderWebApp.CreateScope()) {
                            var scopedProviderWebApp1 = scopeWebApp1.ServiceProvider;
                            var medaitorClient1       = scopedProviderWebApp1.GetRequiredService <IMediatorClientFactory>().GetMedaitorClient();

                            var activityExecutionConfiguration1 = scopedProviderWebApp1.GetRequiredService <ActivityExecutionConfigurationDefaults>().ForQueryCancelable;
                            var request5 = new TestRequest5()
                            {
                                A = 6, B = 7
                            };
                            var connectedClient = await medaitorClient1.ConnectAsync(
                                activityId,
                                request5,
                                activityExecutionConfiguration1,
                                CancellationToken.None);

                            //

                            //medaitorClient2.
                            //
                            var activityResponse = await connectedClient.WaitForAsync(activityExecutionConfiguration1, CancellationToken.None);

                            Assert.NotNull(activityResponse);
                            Assert.NotNull(activityResponse as OkResultActivityResponse <TestResponse5>);
                            Assert.Equal(6 * 7 + 1, ((OkResultActivityResponse <TestResponse5>)activityResponse).Result.R);
                        }
                    }
                }
            }
        }
        public ConcurrentDictionary <int, IServiceProvider> Build()
        {
            var containerDictionary = new ConcurrentDictionary <int, IServiceProvider>();

            using (var scope = _masterServiceCollection.BuildServiceProvider().CreateScope())
            {
                foreach (var tenant in _tenants)
                {
                    //get registrations set for the specific tenant
                    var tenantScopedServiceDescriptors = _masterServiceCollection
                                                         .Where(x => x is TenantScopedServiceDescriptor scopedServiceDescriptor && scopedServiceDescriptor.Tenant.Id == tenant.Id)
                                                         .Select(x => (TenantScopedServiceDescriptor)x);

                    var tenantServiceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
                    foreach (var tenantServiceDescriptor in tenantScopedServiceDescriptors)
                    {
                        tenantServiceCollection.Add(tenantServiceDescriptor);
                    }

                    //get registrations which are not tenant scoped
                    var generalScopeServiceDescriptors = _masterServiceCollection
                                                         .Where(x => x is ServiceDescriptor)
                                                         .ToList();
                    foreach (var serviceDescriptor in generalScopeServiceDescriptors)
                    {
                        if (serviceDescriptor is TenantScopedServiceDescriptor || serviceDescriptor is IServiceCollection || serviceDescriptor.ServiceType == typeof(ContainerBuilder))
                        {
                            continue;
                        }

                        try
                        {
                            var requiredService = scope.ServiceProvider.GetRequiredService(serviceDescriptor.ServiceType);
                            tenantServiceCollection.Add(new ServiceDescriptor(serviceDescriptor.ServiceType, requiredService));
                        }
                        catch
                        {
                            tenantServiceCollection.Add(serviceDescriptor);
                        }
                    }

                    containerDictionary.TryAdd(tenant.Id, tenantServiceCollection.BuildServiceProvider());
                }
            }

            return(containerDictionary);
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddSqlRepo();

            var connectionProvider = Helper.GetConnectionProvider();

            serviceCollection.AddSingleton(connectionProvider);
            serviceCollection.AddSingleton <IGettingStarted, Shared.GettingStarted>();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var gettingStarted = serviceProvider.GetService <IGettingStarted>();

            gettingStarted.DoIt();
        }
Esempio n. 19
0
        private static IServiceProvider InitIoc()
        {
            var Services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var builder  = new ConfigurationBuilder()
                           .SetBasePath(Directory.GetCurrentDirectory())
                           .AddJsonFile("appsettings.json");

            var Configuration = builder.Build();

            ContainerIoC.Register(Services);

            Services.AddOptions();
            Services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));


            return(Services.BuildServiceProvider());
        }
Esempio n. 20
0
        public void MultiTypeRegistrationSingletonsWorkCorrectly()
        {
            // arrange
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var sut = new ContainerSetup(serviceCollection);

            // act
            sut.RetrieveConcretionClassesRequiringRegistration(true);

            // assert
            var services               = serviceCollection.BuildServiceProvider();
            var resolvedClasses        = ((IEnumerable <ITestInterfaceDummy>)services.GetService(typeof(IEnumerable <ITestInterfaceDummy>))).ToList();
            var interfaceResolvedClass = resolvedClasses.FirstOrDefault(t => t.GetType() == typeof(ImplementationClassDummy));
            var directlyResolvedClass  = services.GetService(typeof(ImplementationClassDummy));

            interfaceResolvedClass.Should().Be(directlyResolvedClass);
        }
Esempio n. 21
0
        public void ConcretionClassesFromInterfaceAreCorrectlyResolved()
        {
            // arrange
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
            var sut = new ContainerSetup(serviceCollection);

            // act
            sut.RetrieveConcretionClassesRequiringRegistration(true);

            // assert
            var services        = serviceCollection.BuildServiceProvider();
            var resolvedClasses = ((IEnumerable <ITestInterfaceDummy>)services.GetService(typeof(IEnumerable <ITestInterfaceDummy>))).ToList();

            resolvedClasses.Count.Should().Be(2);
            resolvedClasses.Should().Contain(x => x.GetType() == typeof(ImplementationClassDummy));
            resolvedClasses.Should().Contain(x => x.GetType() == typeof(ImplementationClassTooDummy));
        }
Esempio n. 22
0
        public void ConfigureServices()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
                                              .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
                                              .Where(t => typeof(IController).IsAssignableFrom(t) ||
                                                     t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

            //Register now all repositories
            services.AddTransient <IAccountRepository, AccountRepository>();
            services.AddTransient <IHelperRepository, HelperRepository>();

            var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());

            DependencyResolver.SetResolver(resolver);
        }
Esempio n. 23
0
        public MembershipTests()
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddUserSecrets<Settings>()
                .Build();

            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddWxTeamsSharp();
            var provider = services.BuildServiceProvider();

            _wxTeamsApi = provider.GetRequiredService<IWxTeamsApi>();

            var token = configuration.GetSection("BotToken").Value;
            _wxTeamsApi.Initialize(token);
        }
Esempio n. 24
0
        public void GetRequiredService_TwoConstructorsServicesRegisteredForBoth_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            serviceCollection.AddSingleton(typeof(string), "a");
            serviceCollection.AddSingleton(typeof(int), 1);
            serviceCollection.AddSingleton(typeof(DateTime), 15.June(1980));
            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($@"Unable to activate type '{typeof(TwoConstructors)}'. The following constructors are ambigious:
Void .ctor(System.String, Int32)
Void .ctor(System.DateTime, Int32)");
        }
Esempio n. 25
0
        public void ShouldResolveFactoryRespectingLifestyle()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddSingleton <TestSingleton>();
            serviceCollection.AddTransient <TestTransient>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var transientFactory = serviceProvider.GetRequiredService <IFactory <TestTransient> >();
            var singletonFactory = serviceProvider.GetRequiredService <IFactory <TestSingleton> >();

            transientFactory.New().Should().NotBeSameAs(transientFactory.New());
            serviceProvider.GetRequiredService <TestTransient>().Should().NotBeSameAs(transientFactory.New());

            singletonFactory.New().Should().BeSameAs(singletonFactory.New());
            serviceProvider.GetRequiredService <TestSingleton>().Should().BeSameAs(singletonFactory.New());
        }
Esempio n. 26
0
        public async Task EventLogReadable()
        {
            if (!System.IO.Directory.Exists(latransWrite2Logs))
            {
                System.IO.Directory.CreateDirectory(latransWrite2Logs);
            }

            var filesToDelete = System.IO.Directory.EnumerateFiles(latransWrite2Logs).ToArray();

            foreach (var fileToDelete in filesToDelete)
            {
                System.IO.File.Delete(fileToDelete);
            }

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

            serviceCollection.AddEventLogReadable();
            using (var serviceProvider = serviceCollection.BuildServiceProvider()) {
                var factory         = serviceProvider.GetRequiredService <IEventLogStorageFactory>();
                var eventLogStorage = await factory.CreateAsync(new EventLogStorageOptions()
                {
                    BaseFolder     = latransWrite2Logs,
                    Implementation = "Readable"
                });

                if (eventLogStorage is null)
                {
                    throw new InvalidOperationException("eventLogStorage is null");
                }

                for (int idx = 0; idx < lstWriteDummy.Count; idx++)
                {
                    eventLogStorage.Write(new EventLogRecord()
                    {
                        LgId       = (ulong)idx + 1,
                        DT         = dt.AddMilliseconds(idx),
                        Key        = (idx + 1).ToString(),
                        TypeName   = "Dummy",
                        DataObject = lstWriteDummy[idx]
                    });
                }
                eventLogStorage.Dispose();
            }
        }
        public void UsingValueFunction_CreateByFunction_Test2_Dispose()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddTransient <Dummy>();
            using (var serviceProvider = services.BuildServiceProvider()) {
                var u = UsingValue.CreateByServiceProvider <Dummy>(serviceProvider);
                Assert.NotNull(u);

                // first creation
                var d = u.GetValue();
                Assert.NotNull(d);
                Assert.Same(d, u.GetValue());
                Assert.False(d.IsDisposed);

                u.Dispose();
                Assert.Throws <ObjectDisposedException>(() => { u.GetValue(); });
            }
        }
Esempio n. 28
0
        protected void Application_Start(object sender, EventArgs e)
        {
            //
            // Setup configuration
            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                           .Build();

            //
            // Setup application services + feature management
            IServiceCollection services = new ServiceCollection();

            services.AddSingleton(configuration)
            .AddFeatureManagement();
            services.AddOptions <BCLAppConfig>()
            .Bind(configuration.GetSection("BCLAppConfig"));
            services.AddSingleton <BCLApp>();

            _serviceProvider = services.BuildServiceProvider();
        }
Esempio n. 29
0
        public AdminTests()
        {
            // This is a 12 hour token. It becomes useless and has to be replaced after that time. So need to possibly move these tests
            // to a separate project and not include it outside of local testing.
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddUserSecrets <Settings>()
                                .Build();

            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddWxTeamsSharp();
            var provider = services.BuildServiceProvider();

            _wxTeamsApi = provider.GetRequiredService <IWxTeamsApi>();

            var token = configuration.GetSection("AdminBotToken").Value;

            _wxTeamsApi.Initialize(token);
        }
Esempio n. 30
0
        public void New_FactoryOfTwoArgsForRegisteredInterface_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <ITestInterfaceTwoParams <string, double>, TestServiceTwoParams <string, double> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

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

            var x = factory.New("a", 1.0);

            x.Arg1.Should().Be("a");
            x.Arg2.Should().Be(1.0);

            var y = factory.New("b", 2.0);

            y.Arg1.Should().Be("b");
            y.Arg2.Should().Be(2.0);
        }