Exemplo n.º 1
0
        public MemberSignInManager CreateSut()
        {
            // This all needs to be setup because internally aspnet resolves a bunch
            // of services from the HttpContext.RequestServices.
            var serviceProviderFactory = new DefaultServiceProviderFactory();
            var serviceCollection      = new ServiceCollection();

            serviceCollection
            .AddLogging()
            .AddAuthentication()
            .AddCookie(IdentityConstants.ApplicationScheme);
            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(serviceCollection);
            var httpContextFactory           = new DefaultHttpContextFactory(serviceProvider);
            IFeatureCollection features      = new DefaultHttpContext().Features;

            features.Set <IHttpConnectionFeature>(new HttpConnectionFeature
            {
                LocalIpAddress = IPAddress.Parse("127.0.0.1")
            });
            HttpContext httpContext = httpContextFactory.Create(features);

            _mockLogger = new Mock <ILogger <SignInManager <MemberIdentityUser> > >();
            return(new MemberSignInManager(
                       _memberManager.Object,
                       Mock.Of <IHttpContextAccessor>(x => x.HttpContext == httpContext),
                       CreateClaimsFactory(_memberManager.Object),
                       Mock.Of <IOptions <IdentityOptions> >(),
                       _mockLogger.Object,
                       Mock.Of <IAuthenticationSchemeProvider>(),
                       Mock.Of <IUserConfirmation <MemberIdentityUser> >()));
        }
Exemplo n.º 2
0
        public async Task GetRequest_AllRequests_SuccessfullRead()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddKitchenDomain()
            .AddKitchenApplication()
            .AddKitchenInfrastructure("Server=.;Database=RestaurantManagementSystem;Trusted_Connection=True;MultipleActiveResultSets=true", "S0M3 M4G1C UN1C0RNS G3N3R4T3D TH1S S3CR3T");
            var serviceProviderFactory = new DefaultServiceProviderFactory();

            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(services);

            IMediator Mediator = serviceProvider.GetService <IMediator>();

            var getRequestsQuery  = new GetRequestsQuery();
            var getRequestsResult = await Mediator.Send(getRequestsQuery);

            foreach (var request in getRequestsResult.Requests)
            {
                Assert.IsNotNull(request.Items);
                foreach (var item in request.Items)
                {
                    Assert.IsNotNull(item.Recipe);
                }
            }
        }
        private static void AddPolicies(IServiceCollection services)
        {
            IServiceProvider serviceProvider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var authorizationDataProvider = serviceProvider.GetService <IAuthorizationDataProvider>();

            var policies = authorizationDataProvider?.GetAuthorizationPolicies();

            if (policies == null)
            {
                return;
            }

            var authorizationPolicies = policies as IList <AuthorizationPolicyInfo> ?? policies.ToList();

            if (authorizationPolicies.Any())
            {
                services.AddAuthorization(config =>
                {
                    foreach (var policy in authorizationPolicies)
                    {
                        BuildPolicy(policy, config);
                    }
                });
            }
        }
Exemplo n.º 4
0
        public static async Task Play001Async()
        {
            //Scan all the handler in the Assembly and register them to the serviceProvider
            IServiceProviderFactory <IServiceCollection> serviceProviderFactory = new DefaultServiceProviderFactory();
            IServiceCollection serviceCollection = new ServiceCollection();

            serviceCollection.Scan(scan => scan.FromCallingAssembly()
                                   .AddClasses(classes => classes.InExactNamespaceOf <FooHandler1>())
                                   .AsImplementedInterfaces()
                                   .WithScopedLifetime()
                                   );

            //Register Bahaviors: the registering order is important: in this example the FooMiddleware is invoke before the LoggingMiddleware in the Pipeline
            serviceCollection.AddScoped(typeof(IPipelineBehavior <FooRequest, string>), typeof(FooMiddleware <FooRequest, string>));
            serviceCollection.AddScoped(typeof(IPipelineBehavior <FooRequest, string>), typeof(LoggingMiddleware <FooRequest, string>));

            ILogger <IPipelineBehavior <FooRequest, string> > log = loggerFactory.CreateLogger <LoggingMiddleware <FooRequest, string> >();

            serviceCollection.AddSingleton(log);

            //serviceCollection.AddScoped<FooExceptionHandler>();
            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(serviceCollection);

            //Create a mediator which use the serviceProvider to create the service
            IMediator mediator = new Mediator(t => serviceProvider.GetService(t));

            Console.WriteLine(await mediator.Send(new handlers.FooRequest("foo-1")));
            //Console.WriteLine(await mediator.Send(new handlers.FooRequest("foo-2")));

            //await mediator.Publish(new BarNotification("bar-1"));
        }
Exemplo n.º 5
0
        private static IServiceProvider ConfigureServices(DiscordClient discordClient, LoggingConfiguration loggingConfiguration)
        {
            IServiceCollection services = new ServiceCollection()
                                          .AddLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddNLog(loggingConfiguration);
            })
                                          .AddHttpClient()
                                          .AddDbContext <MonkeyDBContext>(ServiceLifetime.Transient)
                                          .AddSingleton(discordClient)
                                          .AddSingleton <IGuildService, GuildService>()
                                          .AddSingleton <ISchedulingService, SchedulingService>()
                                          .AddSingleton <IReminderService, ReminderService>()
                                          .AddSingleton <IFeedService, FeedService>()
                                          .AddSingleton <IBattlefieldNewsService, BattlefieldNewsService>()
                                          .AddSingleton <IGiveAwaysService, GiveAwaysService>()
                                          .AddSingleton <SteamGameServerService>()
                                          .AddSingleton <MineCraftGameServerService>()
                                          .AddSingleton <IRoleDropdownService, RoleDropdownService>()
                                          .AddSingleton <IChuckService, ChuckService>()
                                          .AddSingleton <ICatService, CatService>()
                                          .AddSingleton <IDogService, DogService>()
                                          .AddSingleton <IXkcdService, XkcdService>()
                                          .AddSingleton <IPictureSearchService, GoogleImageSearchService>()
                                          .AddSingleton <ITriviaService, TriviaService>()
                                          .AddSingleton <IPollService, PollService>()
                                          .AddSingleton <IRoleManagementService, RoleManagementService>()
                                          .AddSingleton <IBenzenFactService, BenzenFactService>();

            IServiceProvider provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            return(provider);
        }
Exemplo n.º 6
0
        protected void ConfigureServer(HostBuilderContext context, IServiceCollection hostServices)
        {
            var services = _currentServices;

            CopyGlobalServices(hostServices, services);

            RegisterBasicServices(context, hostServices, services);

            foreach (var configureServicesAction in ConfigureServicesActions)
            {
                configureServicesAction(context, services);
            }

            RegisterDefaultServices(context, hostServices, services);

            if (_serviceProviderBuilder == null)
            {
                var serviceFactory   = new DefaultServiceProviderFactory();
                var containerBuilder = serviceFactory.CreateBuilder(services);
                ConfigureContainerBuilder(context, containerBuilder);
                _serviceProvider = serviceFactory.CreateServiceProvider(containerBuilder);
            }
            else
            {
                _serviceProvider = _serviceProviderBuilder(context, services);
            }
        }
        public async Task CreateDish_RecipeAlreadyAdded_ExceptionThrown()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddServingDomain()
            .AddServingApplication()
            .AddServingInfrastructure("Server=.;Database=RestaurantManagementSystem;Trusted_Connection=True;MultipleActiveResultSets=true", "S0M3 M4G1C UN1C0RNS G3N3R4T3D TH1S S3CR3T");
            var serviceProviderFactory = new DefaultServiceProviderFactory();

            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(services);

            IMediator Mediator = serviceProvider.GetService <IMediator>();

            var createDishCommand = new CreateDishCommand();

            createDishCommand.Description = "Vkusno";
            createDishCommand.Name        = "Mnogo Vkusna Mandja";
            createDishCommand.RecipeId    = 2;
            createDishCommand.Price       = new Money(10);
            await Mediator.Send(createDishCommand);

            createDishCommand             = new CreateDishCommand();
            createDishCommand.Description = "Vkusno";
            createDishCommand.Name        = "Oshte Po Vkusna Mandja";
            createDishCommand.RecipeId    = 2;
            createDishCommand.Price       = new Money(10);
            await Assert.ThrowsExceptionAsync <InvalidDishException>(() => Mediator.Send(createDishCommand));
        }
        public async Task CreateDish_NewDish_SuccessfullRead()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddServingDomain()
            .AddServingApplication()
            .AddServingInfrastructure("Server=.;Database=RestaurantManagementSystem;Trusted_Connection=True;MultipleActiveResultSets=true", "S0M3 M4G1C UN1C0RNS G3N3R4T3D TH1S S3CR3T");
            var serviceProviderFactory = new DefaultServiceProviderFactory();

            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(services);

            IMediator Mediator = serviceProvider.GetService <IMediator>();

            var createDishCommand = new CreateDishCommand();

            createDishCommand.Description = "Vkusno";
            createDishCommand.Name        = "Vkusna Mandja";
            createDishCommand.RecipeId    = 1;
            createDishCommand.Price       = new Money(10);
            var createDishCommandOutput = await Mediator.Send(createDishCommand);

            var getDishesQuery = new DishesQuery();
            var dbDish         = (await Mediator.Send(getDishesQuery)).Dishes.FirstOrDefault(dish => dish.Id == createDishCommandOutput.DishId);

            Assert.AreEqual(dbDish.Id, createDishCommandOutput.DishId);
            Assert.AreEqual(dbDish.Description, createDishCommand.Description);
            Assert.AreEqual(dbDish.Name, createDishCommand.Name);
            Assert.AreEqual(dbDish.Price, createDishCommand.Price);
            Assert.AreEqual(dbDish.RecipeId, createDishCommand.RecipeId);
        }
Exemplo n.º 9
0
        private static IServiceProvider Setup(Options options, Repository repo)
        {
            IServiceCollection services = new ServiceCollection();
            DiagnosticLogger   logger   = new(options.WarningsAsErrors);

            IBranchSettings branchSettings = new BranchSettings(releaseSuffix: options.ReleaseSuffix, package: options.Package);

            services.AddSingleton <ILogger>(logger);
            services.AddSingleton <IDiagnosticLogger>(logger);
            services.AddSingleton(typeof(ILogger <>), typeof(LoggerProxy <>));

            services.AddSingleton(branchSettings);
            services.AddSingleton(repo);
            services.AddSingleton <IBranchDiscovery, GitBranchDiscovery>();
            services.AddSingleton <IBranchClassification, BranchClassification>();
            services.AddSingleton <IVersionPublisher, GitHubActionsVersionPublisher>();
            services.AddSingleton <IVersionPublisher, TeamCityVersionPublisher>();
            services.AddSingleton <IVersionDetector, VersionDetector>();

            services.AddSingleton <IExternalBranchLocator, GitHubRefEnvironmentVariableBranchLocator>();
            services.AddSingleton <IExternalBranchLocator, GitBranchEnvironmentVariableBranchLocator>();

            IServiceProviderFactory <IServiceCollection> spf = new DefaultServiceProviderFactory();

            return(spf.CreateServiceProvider(services));
        }
Exemplo n.º 10
0
        public async Task <IServiceProvider> ConfigureServices()
        {
            var services = new ServiceCollection()
                           .AddSingleton <DatabaseHandler>()
                           .AddSingleton <ChessHandler>()
                           .AddSingleton <GuildHandler>()
                           .AddSingleton <BlackJackHandler>()
                           .AddSingleton <ChessStatsHandler>()
                           .AddSingleton <SchedulerService>()
                           .AddSingleton <CommandManager>()
                           .AddSingleton <RoslynManager>()
                           .AddSingleton <Random>()
                           .AddSingleton <ChessHelper>()
                           .AddSingleton <HttpClient>()
                           .AddSingleton <AssetService>()
                           .AddSingleton <ChessService>()
                           .AddSingleton <WebhookService>()
                           .AddSingleton <BlackJackService>()
                           .AddSingleton <InteractiveService>()
                           .AddSingleton <GuildHelper>()
                           .AddSingleton <WebhookService>()
                           .AddSingleton <DatabaseHandler>()
                           .AddSingleton <ChessGame>();

            // Discord
            await LoadDiscordAsync(services);

            // Google
            await LoadGoogleAsync(services);

            var provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            return(provider);
        }
        public async Task GetOrders_AllOrders_SuccessfulRead()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddServingDomain()
            .AddServingApplication()
            .AddServingInfrastructure("Server=.;Database=RestaurantManagementSystem;Trusted_Connection=True;MultipleActiveResultSets=true", "S0M3 M4G1C UN1C0RNS G3N3R4T3D TH1S S3CR3T");
            var serviceProviderFactory = new DefaultServiceProviderFactory();

            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(services);

            IMediator Mediator = serviceProvider.GetService <IMediator>();

            var getOrdersQuery = new OrdersQuery();
            var dbOrders       = await Mediator.Send(getOrdersQuery);

            foreach (var order in dbOrders.Orders)
            {
                Assert.IsNotNull(order.Items);
                foreach (var item in order.Items)
                {
                    Assert.IsNotNull(item.Dish);
                }
            }
        }
Exemplo n.º 12
0
#pragma warning restore CA2000 // Dispose objects before losing scope

        private static IServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection();

            services.AddSingleton <ILoggerFactory, LoggerFactory>();
            services.AddSingleton(typeof(ILogger <>), typeof(Logger <>));
            services.AddLogging((builder) => builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace));
            services.AddDbContext <MonkeyDBContext>(ServiceLifetime.Transient);
            services.AddSingleton <DiscordSocketClient, MonkeyClient>();
            services.AddSingleton <InteractiveService>();
            services.AddSingleton <CommandService, MonkeyCommandService>();
            services.AddSingleton <CommandManager>();
            services.AddSingleton <ISchedulingService, SchedulingService>();
            services.AddSingleton <IAnnouncementService, AnnouncementService>();
            services.AddSingleton <ITriviaService, OTDBTriviaService>();
            services.AddSingleton <IFeedService, FeedService>();
            services.AddSingleton <IBattlefieldNewsService, BattlefieldNewsService>();
            services.AddSingleton <SteamGameServerService>();
            services.AddSingleton <MineCraftGameServerService>();
            services.AddSingleton <IGameSubscriptionService, GameSubscriptionService>();
            services.AddSingleton <IRoleButtonService, RoleButtonService>();
            services.AddSingleton <IChuckService, ChuckService>();
            services.AddSingleton <IPictureUploadService, CloudinaryPictureUploadService>();
            services.AddSingleton <IDogService, DogService>();
            services.AddSingleton <IXkcdService, XkcdService>();

            var provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            return(provider);
        }
Exemplo n.º 13
0
        private async void CreateRolesandUsers()
        {
            ApplicationDbContext context   = new ApplicationDbContext(new DbContextOptions <ApplicationDbContext>());
            var            serviceProvider = new DefaultServiceProviderFactory().CreateServiceProvider(new ServiceCollection());
            var            roleManager     = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context), new List <RoleValidator <IdentityRole> >(), new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), new Logger <RoleManager <IdentityRole> >(new LoggerFactory()));
            var            UserManager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context), Options.Create <IdentityOptions>(new IdentityOptions()), new PasswordHasher <ApplicationUser>(Options.Create <PasswordHasherOptions>(new PasswordHasherOptions())), new List <UserValidator <ApplicationUser> >(), new List <PasswordValidator <ApplicationUser> >(), new UpperInvariantLookupNormalizer(), new IdentityErrorDescriber(), serviceProvider, new Logger <UserManager <ApplicationUser> >(new LoggerFactory()));
            IdentityResult result;

            if (await UserManager.FindByNameAsync("*****@*****.**") is ApplicationUser user)
            {
                result = await UserManager.AddToRoleAsync(user, "Admin");
            }
            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!await roleManager.RoleExistsAsync("Admin"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNetCore.Identity.IdentityRole("admin")
                {
                    Name = "Admin"
                };
                await roleManager.CreateAsync(role);

                //Here we create a Admin super user who will maintain the website

                //var user = new ApplicationUser();
                //user.UserName = "******";
                //user.Email = "*****@*****.**";

                //string userPWD = "Peevee1998!";

                //var chkUser = await UserManager.CreateAsync(user, userPWD);

                ////Add default User to Role Admin
                //if (chkUser.Succeeded)
                //{
                //    var result1 = UserManager.AddToRoleAsync(user, "Admin");

                //}
            }

            // creating Creating Manager role
            if (!await roleManager.RoleExistsAsync("User"))
            {
                var role = new Microsoft.AspNetCore.Identity.IdentityRole("User")
                {
                    Name = "User"
                };
                await roleManager.CreateAsync(role);
            }

            // creating Creating Employee role
            if (!await roleManager.RoleExistsAsync("Employee"))
            {
                var role = new Microsoft.AspNetCore.Identity.IdentityRole
                {
                    Name = "Employee"
                };
                await roleManager.CreateAsync(role);
            }
        }
Exemplo n.º 14
0
#pragma warning restore CA2000 // Dispose objects before losing scope

        private static IServiceProvider ConfigureServices(Action <ILoggingBuilder> configureLogging)
        {
            IServiceCollection services = new ServiceCollection()
                                          .AddLogging(configureLogging)
                                          .AddHttpClient()
                                          .AddDbContext <MonkeyDBContext>(ServiceLifetime.Transient)
                                          .AddSingleton <DiscordSocketClient, MonkeyClient>()
                                          .AddSingleton <InteractiveService>()
                                          .AddSingleton <CommandService, MonkeyCommandService>()
                                          .AddSingleton <CommandManager>()
                                          .AddSingleton <IGuildService, GuildService>()
                                          .AddSingleton <ISchedulingService, SchedulingService>()
                                          .AddSingleton <IAnnouncementService, AnnouncementService>()
                                          .AddSingleton <ITriviaService, OTDBTriviaService>()
                                          .AddSingleton <IFeedService, FeedService>()
                                          .AddSingleton <IBattlefieldNewsService, BattlefieldNewsService>()
                                          .AddSingleton <SteamGameServerService>()
                                          .AddSingleton <MineCraftGameServerService>()
                                          .AddSingleton <IGameSubscriptionService, GameSubscriptionService>()
                                          .AddSingleton <IRoleButtonService, RoleButtonService>()
                                          .AddSingleton <IChuckService, ChuckService>()
                                          .AddSingleton <ICatService, CatService>()
                                          .AddSingleton <IDogService, DogService>()
                                          .AddSingleton <IXkcdService, XkcdService>()
                                          .AddSingleton <IPictureSearchService, GoogleImageSearchService>();

            IServiceProvider provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            return(provider);
        }
Exemplo n.º 15
0
        private void reconnect()
        {
            bridge.Userconnecterror = true;
            while (bridge.Userconnecterror == true)
            {
                ;
            }
            Program.setuserinfo();
            TaskScheduler.UnobservedTaskException += Program.TaskScheduler_UnobservedTaskException;
            var spFactory = new DefaultServiceProviderFactory();
            var sc        = new ServiceCollection();

            Program.ConfigureServices(sc);
            var spBuilder     = spFactory.CreateBuilder(sc);
            var container     = spFactory.CreateServiceProvider(spBuilder);
            var loggerFactory = container.GetRequiredService <ILoggerFactory>();

            using (var demo = container.GetRequiredService <FBoxDemo>())
            {
                demo.Go().Wait();
                string ln;
                do
                {
                    ln = "";// Console.ReadLine();
                } while (ln != "quit");
            }
        }
Exemplo n.º 16
0
    public void ActivateTest()
    {
        var serviceCollection = new ServiceCollection();

        serviceCollection.AddSingleton("S");
        var services = new DefaultServiceProviderFactory()
                       .CreateServiceProvider(serviceCollection);

        var a = services.Activate <A>();

        a.X.Should().Be("S");
        a.Y.Should().Be("S");

        var b = services.Activate <B>();

        b.X.Should().Be("S");
        b.Y.Should().BeEmpty();

        ((Action)(() => {
            var c = services.Activate <C>();
        })).Should().Throw <InvalidOperationException>();

        var c = services.Activate <C>(1, 2);

        c.X.Should().Be("1");
        c.Y.Should().Be("2");
    }
Exemplo n.º 17
0
        public async Task StartAsync()
        {
            IServiceCollection services;
            IServiceProvider   provider;


            try
            {
                _config = Configuration.ConfigurationReader.Load();
            }
            catch
            {
                // Catch the error and show a dialog. The error will be logged when trying to load the config
                // file anyway, so all we need to do here is to ensure that the user knows why the application crashed.
                MessageBox.Show(
                    "An error occurred whilst trying to load the configuration file. Please ensure the configuration file exists and is named correctly.",
                    "Invalid Configuration File",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );
            }

            _commands = new CommandService(
                new CommandServiceConfig
            {
                DefaultRunMode = RunMode.Async,
                LogLevel       = LogSeverity.Verbose
            }
                );

            _client = new DiscordSocketClient(
                new DiscordSocketConfig
            {
                LogLevel         = LogSeverity.Verbose,
                MessageCacheSize = 1000
            }
                );

            // Add singletons of all the services we will need.
            services = new ServiceCollection()
                       .AddSingleton(_client)
                       .AddSingleton(_commands)
                       .AddSingleton <CommandHandler>()
                       .AddSingleton <LoggingService>()
                       .AddSingleton <StartupService>()
                       .AddSingleton(_config);

            // Create the service provider.
            provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            // Initialize all the services.
            provider.GetRequiredService <LoggingService>();
            await provider.GetRequiredService <StartupService>().StartAsync();

            provider.GetRequiredService <CommandHandler>();

            // Prevent the application from closing.
            await Task.Delay(-1);
        }
Exemplo n.º 18
0
        private IServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection()
                           .AddSingleton(DiscordClient);
            var provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            return(provider);
        }
        public static IServiceProvider GetServiceProviderInstance()
        {
            var factory           = new DefaultServiceProviderFactory();
            var serviceCollection = new ServiceCollection();

            factory.CreateBuilder(serviceCollection);
            return(factory.CreateServiceProvider(serviceCollection));
        }
        private IServiceProvider CreateServiceProvider()
        {
            var factory = new DefaultServiceProviderFactory();

            return(factory.CreateServiceProvider(
                       new ServiceCollection().AddGybs(builder => builder.AddAttributeServices())
                       ));
        }
Exemplo n.º 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultBootstrapper"/> class.
 /// </summary>
 /// <param name="assemblies">The assemblies.</param>
 /// <param name="collection">The collection.</param>
 public DefaultBootstrapper(IEnumerable <Assembly> assemblies, IEnumerable <ServiceDescriptor> collection)
     : base(assemblies)
 {
     AppContainer = (IServiceCollection)collection;
     Register(this);
     Register <IBootstrapper>(this);
     ServiceProviderFactory = new DefaultServiceProviderFactory();
 }
        internal static object QuickResolve(this IServiceCollection services, Type targetType)
        {
            var serviceProviderFactory = new DefaultServiceProviderFactory();
            var serviceProvider        = serviceProviderFactory.CreateServiceProvider(services);

            var instance = serviceProvider.CreateScope().ServiceProvider.GetRequiredService(targetType);

            return(instance);
        }
Exemplo n.º 23
0
        private IOperationBus CreateBus()
        {
            var logger          = Substitute.For <ILogger <ServiceProviderOperationBus> >();
            var serviceProvider = new DefaultServiceProviderFactory().CreateServiceProvider(
                new ServiceCollection().AddGybs(builder => builder.AddOperationHandlers())
                );

            return(new ServiceProviderOperationBus(logger, serviceProvider));
        }
Exemplo n.º 24
0
        public IServiceProvider ConfigureServices()
        {
            var services = new ServiceCollection().AddSingleton(client).AddSingleton(new CommandService(new CommandServiceConfig {
                CaseSensitiveCommands = false
            }));
            var provider = new DefaultServiceProviderFactory().CreateServiceProvider(services);

            return(provider);
        }
Exemplo n.º 25
0
        private IValidator CreateValidator()
        {
            var logger          = Substitute.For <ILogger <Validator> >();
            var serviceProvider = new DefaultServiceProviderFactory().CreateServiceProvider(
                new ServiceCollection()
                .AddGybs(builder => builder.AddValidation())
                );

            return(new Validator(logger, serviceProvider));
        }
Exemplo n.º 26
0
        public DefaultDomainServiceProvider(ICommunicationModelProvider communicationModelProvider)
        {
            _communicationModelProvider = communicationModelProvider;

            var serviceCollection = new ServiceCollection();

            AddDomainServicesViaDasync(serviceCollection, _communicationModelProvider.Model);

            var serviceProvider = new DefaultServiceProviderFactory().CreateServiceProvider(serviceCollection);
        }
Exemplo n.º 27
0
        internal IServiceProvider CreateServiceProviderCore(IServiceCollection services)
        {
            var serviceProviderFactory = new DefaultServiceProviderFactory(new ServiceProviderOptions());

            IServiceCollection builder = new ServiceCollection
            {
                defaultServices.Concat(addedShellServices).Concat(services)
            };

            return(serviceProviderFactory.CreateServiceProvider(serviceProviderFactory.CreateBuilder(builder)));
        }
Exemplo n.º 28
0
        private static IHttpClientFactory CreateHttpClientFactory()
        {
            var services = new ServiceCollection();

            services.AddHttpClient();

            var serviceProviderFactory = new DefaultServiceProviderFactory();
            var serviceProvider        = serviceProviderFactory.CreateServiceProvider(services);

            return(serviceProvider.GetRequiredService <IHttpClientFactory>());
        }
Exemplo n.º 29
0
        /// <summary>
        /// 创建容器
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection CreateServiceBuilder(IServiceCollection services = null)
        {
            var factory = new DefaultServiceProviderFactory();

            if (services == null)
            {
                services = _container;
            }
            _container = factory.CreateBuilder(services);
            return(_container);
        }
        public CustomExportProvider(IServiceCollection services)
        {
            Services       = services;
            ServicesByType = Services.ToLookup(d => d.ServiceType);
            var sp = new DefaultServiceProviderFactory(new ServiceProviderOptions()
            {
                ValidateScopes = true
            });

            Log.Debug("Creating ServiceScope for type resolution.");
            ServiceProvider = sp.CreateServiceProvider(services).CreateScope().ServiceProvider;
        }