Exemple #1
0
        public IServiceProvider GetServiceProvider()
        {
            var env = new TestWebHostEnviroment();

            env.EnvironmentName = "development";
            var services      = new ServiceCollection();
            var configBuilder = new ConfigurationBuilder();

            JsonConfigurationExtensions.AddJsonFile(configBuilder, "appsettings.json", true, true);
            Configuration = configBuilder.Build();
            services.AddLogging(builder =>
            {
                builder.ClearProviders();
                if (env.EnvironmentName.Contains("develop", StringComparison.OrdinalIgnoreCase))
                {
                    //分环境不同来配置log
                }
                builder.AddDebug();
                builder.AddConsole();
                builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            });
            var startUp = new Startup(Configuration, env);

            startUp.ConfigureServices(services);
            var autofacServiceProviderFactory = new AutofacServiceProviderFactory(startUp.ConfigureContainer);
            var containerBuilder = autofacServiceProviderFactory.CreateBuilder(services);

            return(autofacServiceProviderFactory.CreateServiceProvider(containerBuilder));
        }
Exemple #2
0
        private IMediator BuildMediator()
        {
            var services = new ServiceCollection();

            DIHelper.ConfigureServices(services);

            services.AddDbContext <IDbContext, AppDbContext>(options =>
                                                             options.UseInMemoryDatabase(Guid.NewGuid().ToString()));

            var serviceProviderFactory = new AutofacServiceProviderFactory();
            var containerBuilder       = serviceProviderFactory.CreateBuilder(services);
            var serviceProvider        = serviceProviderFactory.CreateServiceProvider(containerBuilder);

            var mediator = serviceProvider.GetRequiredService <IMediator>();

            var dbContext = serviceProvider.GetRequiredService <IDbContext>();

            dbContext.Orders.AddRange(
                new Order {
                Id = 1, UserEmail = "*****@*****.**"
            },
                new Order {
                Id = 2, UserEmail = "other_email"
            });
            dbContext.SaveChangesAsync().Wait();

            return(mediator);
        }
Exemple #3
0
        public static IServiceProvider CreateBuilder(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .Build();

            var services = new ServiceCollection()
                           .AddLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddNLog(config);
            });

            var factory = new AutofacServiceProviderFactory();

            var startup = new Startup(config);

            startup.ConfigureServices(services);
            var builder = factory.CreateBuilder(services);

            startup.ConfigureContainer(builder);
            var provider = factory.CreateServiceProvider(builder);

            return(provider);
        }
        public ContainerBuilder CreateBuilder(IServiceCollection services)
        {
            var builder = _decorateer.CreateBuilder(services);

            PopulateAutoFacContainer(services, builder, _configurationBuilder, _logger);
            return(builder);
        }
        public static ContainerBuilder BuildContainer(IServiceCollection services)
        {
            var factory = new AutofacServiceProviderFactory();
            var cb      = factory.CreateBuilder(services);

            return(cb);
        }
Exemple #6
0
        public virtual ContainerBuilder CreateBuilder(IServiceCollection services)
        {
            _services = services;
            ContainerBuilder containerBuilder = _inner.CreateBuilder(services);

            return(containerBuilder);
        }
Exemple #7
0
        private static ContainerBuilder BuildContainer(IServiceCollection services)
        {
            var factory = new AutofacServiceProviderFactory();
            var result  = factory.CreateBuilder(services);

            return(result);
        }
Exemple #8
0
        protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection)
        {
            var factory = new AutofacServiceProviderFactory();
            var builder = factory.CreateBuilder(serviceCollection);

            return(factory.CreateServiceProvider(builder));
        }
Exemple #9
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            Rg.Plugins.Popup.Popup.Init(this, bundle);

            Forms.Init(this, bundle);

            // Initializing FFImageLoading
            CachedImageRenderer.Init(false);

            // Initializing User Dialogs
            UserDialogs.Init(this);

            // Initializing Xamarin Essentials
            Xamarin.Essentials.Platform.Init(this, bundle);

#if GORILLA
            LoadApplication(UXDivers.Gorilla.Droid.Player.CreateApplication(
                                this,
                                new UXDivers.Gorilla.Config("Good Gorilla")
                                .RegisterAssemblyFromType <InverseBooleanConverter>()
                                .RegisterAssemblyFromType <CachedImageRenderer>()));
#else
            //Loading dependent libindy
            JavaSystem.LoadLibrary("gnustl_shared");
            JavaSystem.LoadLibrary("indy");

            // Initializing QR Code Scanning support
            ZXing.Net.Mobile.Forms.Android.Platform.Init();

            //Marshmellow and above require permission requests to be made at runtime
            if ((int)Build.VERSION.SdkInt >= 23)
            {
                CheckAndRequestRequiredPermissions();
            }


            var services = new ServiceCollection(); //Create a service collection
            services.AddHttpClient();               //invoke add http client extension
            services.AddOptions();

            //...add other services as needed

            //use autofac integration `Autofac.Extensions.DependencyInjection`
            var providerFactory = new AutofacServiceProviderFactory();

            //OR Container
            ContainerBuilder builder = providerFactory.CreateBuilder(services);
            builder.RegisterModule(new PlatformModule());

            var container = builder.Build();

            LoadApplication(new App(container));
#endif
        }
        public void CreateBuilderAllowsForNullConfigurationAction()
        {
            var factory = new AutofacServiceProviderFactory();

            var builder = factory.CreateBuilder(new ServiceCollection());

            Assert.NotNull(builder);
        }
        public void CreateBuilderReturnsNewInstance()
        {
            var factory = new AutofacServiceProviderFactory();

            var builder = factory.CreateBuilder(new ServiceCollection());

            Assert.NotNull(builder);
        }
        public void CreateBuilderExecutesConfigurationActionWhenProvided()
        {
            var factory = new AutofacServiceProviderFactory(config => config.Register(c => "Foo"));

            var builder = factory.CreateBuilder(new ServiceCollection());

            Assert.Equal("Foo", builder.Build().Resolve <string>());
        }
        public void CreateServiceProviderBuildsServiceProviderUsingContainerBuilder()
        {
            var factory  = new AutofacServiceProviderFactory();
            var services = new ServiceCollection().AddTransient <object>();
            var builder  = factory.CreateBuilder(services);

            var serviceProvider = factory.CreateServiceProvider(builder);

            Assert.NotNull(serviceProvider.GetService(typeof(object)));
        }
Exemple #14
0
        public void CreateServiceProviderUsesDefaultContainerBuildOptionsWhenNotProvided()
        {
            var factory  = new AutofacServiceProviderFactory();
            var services = new ServiceCollection().AddSingleton("Foo");
            var builder  = factory.CreateBuilder(services);

            var serviceProvider = factory.CreateServiceProvider(builder);

            Assert.NotNull(serviceProvider.GetService <Lazy <string> >());
        }
        protected void Application_Start()
        {
            var services = new ServiceCollection();

            services.AddDistributedMemoryCache(); //Token cache için gerekli
            services.AddePlatformClients(clientOptions =>
            {
                clientOptions.AuthServiceUrl    = "https://coretest.isim360.com";
                clientOptions.InvoiceServiceUrl = "https://efaturaservicetest.isim360.com";
                clientOptions.Auth = new ClientOptions.AuthOption
                {
                    ClientId = "serviceApi",
                    Username = "******",
                    Password = "******"
                };
            });

            var providerFactory = new AutofacServiceProviderFactory();
            //to populate your container
            ContainerBuilder builder = providerFactory.CreateBuilder(services);

            //var builder = new ContainerBuilder();

            // MVC - Register your MVC controllers.
            builder.RegisterControllers(typeof(WebApiApplication).Assembly);

            // MVC - OPTIONAL: Register model binders that require DI.
            builder.RegisterModelBinders(typeof(WebApiApplication).Assembly);
            builder.RegisterModelBinderProvider();

            // MVC - OPTIONAL: Register web abstractions like HttpContextBase.
            builder.RegisterModule <AutofacWebTypesModule>();

            // MVC - OPTIONAL: Enable property injection in view pages.
            builder.RegisterSource(new ViewRegistrationSource());

            // MVC - OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            // ePlatform Services
            //builder.RegisterModule<ePlatformSerivecesModule>();

            // MVC - Set the dependency resolver to be Autofac.
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Standard MVC setup:

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Exemple #16
0
        public void CreateServiceProviderUsesContainerBuildOptionsWhenProvided()
        {
            var options  = ContainerBuildOptions.ExcludeDefaultModules;
            var factory  = new AutofacServiceProviderFactory(options);
            var services = new ServiceCollection().AddSingleton("Foo");
            var builder  = factory.CreateBuilder(services);

            var serviceProvider = factory.CreateServiceProvider(builder);

            Assert.Null(serviceProvider.GetService <Lazy <string> >());
        }
        public void CreateBuilderReturnsInstanceWithServicesPopulated()
        {
            var factory  = new AutofacServiceProviderFactory();
            var services = new ServiceCollection();

            services.AddTransient <object>();

            var builder = factory.CreateBuilder(services);

            Assert.True(builder.Build().IsRegistered <object>());
        }
Exemple #18
0
        private static IServiceProvider CreateServiceProvider(ServiceCollection services)
        {
            var autofacServiceProviderFactory =
                new AutofacServiceProviderFactory(builder => builder.RegisterModule(new AutoRegistrationModule()));

            services.AddSingleton <IServiceProviderFactory <ContainerBuilder> >(autofacServiceProviderFactory);
            var containerBuilder = autofacServiceProviderFactory.CreateBuilder(services);
            var serviceProvider  = autofacServiceProviderFactory.CreateServiceProvider(containerBuilder);

            return(serviceProvider);
        }
Exemple #19
0
        public void CanProvideContainerBuildOptionsAndConfigurationAction()
        {
            var factory = new AutofacServiceProviderFactory(
                ContainerBuildOptions.ExcludeDefaultModules,
                config => config.Register(c => "Foo"));
            var builder = factory.CreateBuilder(new ServiceCollection());

            var serviceProvider = factory.CreateServiceProvider(builder);

            Assert.NotNull(serviceProvider.GetService <string>());
            Assert.Null(serviceProvider.GetService <Lazy <string> >());
        }
Exemple #20
0
        private IServiceProvider CreateServiceProvider(IServiceCollection services)
        {
            var autofacServiceProviderFactory =
                new AutofacServiceProviderFactory(builder => builder.RegisterModule(new AutoRegistrationModule()));
            var containerBuilder = autofacServiceProviderFactory.CreateBuilder(services);

            ConfigureContainer(containerBuilder);

            var serviceProvider = autofacServiceProviderFactory.CreateServiceProvider(containerBuilder);

            return(serviceProvider);
        }
        private static IServiceProvider CreateAutofacServiceProvider(Startup startup, ServiceCollection services)
        {
            var autofactSPFactory = new AutofacServiceProviderFactory();

            var builder = autofactSPFactory.CreateBuilder(services);

            startup.ConfigureContainer(builder);

            var serviceProvider = autofactSPFactory.CreateServiceProvider(builder);

            return(serviceProvider);
        }
Exemple #22
0
        private void InitializeENode()
        {
            JaneConfiguration.Create();

            var services = new ServiceCollection();

            ConfigureService(services);

            var serviceProviderFactory = new AutofacServiceProviderFactory();
            var containerBuilder       = serviceProviderFactory.CreateBuilder(services);

            ConfigureContainer(containerBuilder);

            var serviceProvider = serviceProviderFactory.CreateServiceProvider(containerBuilder);

            serviceProvider.PopulateJaneENodeDIContainer();

            JaneConfiguration.Instance.CreateAutoMapperMappings();
            JaneConfiguration.Instance.RegisterBackgroundJob(_bussinessAssemblies);

            ENodeConfiguration.Instance.InitializeBusinessAssemblies(_bussinessAssemblies);

            var enodeConfig = ObjectContainer.Resolve <IENodeConfiguration>();

            ENodeConfiguration.Instance
            .InitializeRedisLockService(new RedisOptions()
            {
                ConnectionString = enodeConfig.LockServiceConnectionString,
                DatabaseId       = enodeConfig.LockServiceDatabaseId
            },
                                        "RedisLockPrefix")
            .InitializeMongoDbEventStore(new ENode.Configurations.MongoDbConfiguration()
            {
                ConnectionString = enodeConfig.EventStoreConnectionString,
                DatabaseName     = enodeConfig.EventStoreDatabaseName
            },
                                         "BoundedContextEventStream")
            .InitializeMongoDbPublishedVersionStore(new ENode.Configurations.MongoDbConfiguration()
            {
                ConnectionString = enodeConfig.EventStoreConnectionString,
                DatabaseName     = enodeConfig.EventStoreDatabaseName
            },
                                                    "BoundedContextPublishedVersion")
            .InitializeMySqlAggregateSnapshotter(
                enodeConfig.AggregateSnapshotConnectionString,
                "BoundedContextAggregateSnapshot"
                )
            .StartKafka()
            .Start();
        }
Exemple #23
0
        public async Task CheckOrderTest()
        {
            var services = new ServiceCollection();

            DIHelper.ConfigureServices(services);

            services.AddDbContext <IReadOnlyDbContext, ReadOnlyAppDbContext>(builder =>
                                                                             builder.UseInMemoryDatabase("Test"));
            services.AddDbContext <IDbContext, AppDbContext>(builder =>
                                                             builder.UseInMemoryDatabase("Test"));

            var factory = new AutofacServiceProviderFactory();
            var builder = factory.CreateBuilder(services);
            var sp      = factory.CreateServiceProvider(builder);

            var dbContext = sp.GetRequiredService <IDbContext>();

            dbContext.Orders.AddRange(new[]
            {
                new Order {
                    Id = 1, UserEmail = "*****@*****.**"
                },
                new Order {
                    Id = 2, UserEmail = "other"
                }
            });
            await dbContext.SaveChangesAsync();

            var dispatcher = sp.GetRequiredService <IHandlerDispatcher>();

            var get1Result = await dispatcher.SendAsync(new GetOrderByIdQuery { Id = 1 });

            Func <Task <OrderDto> > get2Delegate = () => dispatcher.SendAsync(new GetOrderByIdQuery {
                Id = 2
            });

            Assert.Equal(1, get1Result.Id);
            await Assert.ThrowsAsync <Exception>(get2Delegate);

            var update1Result = await dispatcher.SendAsync(new UpdateOrderCommand { Id = 1, Dto = new ChangeOrderDto() });

            Func <Task <Unit> > update2Delegate = () => dispatcher.SendAsync(new UpdateOrderCommand()
            {
                Id = 2, Dto = new ChangeOrderDto()
            });

            await Assert.ThrowsAsync <Exception>(update2Delegate);
        }
        public static void AutofacSample()
        {
            try
            {
                IServiceProviderFactory <ContainerBuilder> serviceProviderFactory = new AutofacServiceProviderFactory();

                #region Register all implementations / objects in the dependency graph

                IServiceCollection serviceCollection = new ServiceCollection();
                serviceCollection.AddScoped(typeof(IWalletRepository), svp => new WalletRepository("LocalDB_connection_string"));
                //serviceCollection.AddTransient(typeof(IWalletService), typeof(WalletService));

                #endregion Register all implementations / objects in the dependency graph

                ContainerBuilder containerBuilder = serviceProviderFactory.CreateBuilder(serviceCollection);
                // via assembly scan
                containerBuilder.RegisterAssemblyTypes(typeof(WalletService).GetTypeInfo().Assembly)
                .Except <WalletRepository>()
                .AsImplementedInterfaces();

                // or individually
                //containerBuilder.RegisterType<MyHandler>().AsImplementedInterfaces().InstancePerDependency();

                IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(containerBuilder);

                //from here it is exactly the same as the above example

                using (var controller01Scope = serviceProvider.CreateScope())
                {
                    IServiceProvider scopedServiceProvider = controller01Scope.ServiceProvider;
                    {
                        IWalletService walletService = scopedServiceProvider.GetService <IWalletService>();
                        walletService.LockAmount();
                    }
                    {
                        IWalletService walletService = scopedServiceProvider.GetService <IWalletService>();
                        walletService.LockAmount();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <inheritdoc/>
        public ContainerBuilder CreateBuilder(IServiceCollection services)
        {
            ApplyLoggerFactoryWorkarounds(services);

            var builder = _autofacFactory.CreateBuilder(services);

            var bootResult = Bootloader.Configure(_ =>
            {
                if (_context.HostingEnvironment.IsDevelopment())
                {
                    _.Development();
                }
                _.SkipBootprocedures();
                _.UseContainer <ServiceProviderContainer>();
            }).Start();

            builder.AddDolittle(bootResult.Assemblies, bootResult.Bindings);

            return(builder);
        }
        private static IHostBuilder CreateDefaultHostBuilder(Type startupType)
        {
            // Define the root application builder, used for defining middleware and other application components
            UOWApplication applicationBuilder = new UOWApplication();
            AutofacServiceProviderFactory autofacServiceProviderFactory = new AutofacServiceProviderFactory();

            // Create a root serviceProvider and add the Startup type into the container
            ServiceCollection serviceDescriptors = new ServiceCollection();

            serviceDescriptors.AddSingleton <UOWApplication>(applicationBuilder);

            ContainerBuilder builder = autofacServiceProviderFactory.CreateBuilder(serviceDescriptors);

            if (startupType != null)
            {
                builder.RegisterType(startupType).SingleInstance().AsSelf().As <UOWStartup>();
            }

            IServiceProvider rootServiceProvider = autofacServiceProviderFactory.CreateServiceProvider(builder);

            // Get the root lifetime scope to be used as the appHost's parent container
            ILifetimeScope rootLifetimeScope = rootServiceProvider.GetRequiredService <ILifetimeScope>();

            IHostBuilder appHostBuilder = Host.CreateDefaultBuilder()
                                          .UseWindowsService()
                                          .UseServiceProviderFactory(new AutofacChildLifetimeScopeServiceProviderFactory(rootLifetimeScope))
                                          .ConfigureServices(ConfigureServices);

            if (startupType != null)
            {
                // Resolve the Startup type so the end use can inject into the constructor
                UOWStartup startup = rootServiceProvider.GetRequiredService(startupType) as UOWStartup;

                // Startup may register some dependencies
                appHostBuilder.ConfigureServices(startup.ConfigureServices);
                applicationBuilder.Startup = startup;
            }

            return(appHostBuilder);
        }
        private void InitializeENode()
        {
            var services = new ServiceCollection();

            ConfigureService(services);

            var serviceProviderFactory = new AutofacServiceProviderFactory();
            var containerBuilder       = serviceProviderFactory.CreateBuilder(services);

            ConfigureContainer(containerBuilder);

            var serviceProvider = serviceProviderFactory.CreateServiceProvider(containerBuilder);

            ObjectContainer.Current.SetContainer(serviceProvider.GetAutofacRoot());

            ENodeConfiguration.Instance.InitializeBusinessAssemblies(_bussinessAssemblies);

            var eventStoreConnectionString = Root["ENode:EventStoreConnectionString"];
            var eventStoreDatabase         = Root["ENode:EventStoreDatabaseName"];

            ENodeConfiguration.Instance
            .InitializeMongoDbEventStore(new MongoDbConfiguration()
            {
                ConnectionString = eventStoreConnectionString,
                DatabaseName     = eventStoreDatabase
            })
            .InitializeMongoDbPublishedVersionStore(new MongoDbConfiguration()
            {
                ConnectionString = eventStoreConnectionString,
                DatabaseName     = eventStoreDatabase
            })
            .InitializeMongoDbAggregateSnapshotter(new MongoDbConfiguration()
            {
                ConnectionString = eventStoreConnectionString,
                DatabaseName     = eventStoreDatabase
            })
            .StartKafka()
            .Start();
        }
Exemple #28
0
        public ContainerBuilder CreateBuilder(IServiceCollection services)
        {
            _services = services;

            return(_wrapped.CreateBuilder(services));
        }