Пример #1
0
        static void Main(string[] args)
        {
            var options = new Options();

            if (args.Length > 0 && CommandLine.Parser.Default.ParseArguments(args, options))
            {
                var connection = options.ToConnection();
                using (var scope = new AutofacBootstrapper(connection)) {
                    try {
                        var result  = scope.Resolve <IImporter>().Import(connection);
                        var profile = scope.Resolve <IProfiler>().Profile(result, options.Limit);
                        System.Console.Out.WriteLine("Name,Type,Position,Count,Min Value,Max Value,Min Length,Max Length");
                        foreach (var field in profile)
                        {
                            System.Console.Out.WriteLine($"{field.Field.Name},{field.Field.Type},{field.Field.Index - 3},{field.Count},\"{field.MinValue}\",\"{field.MaxValue}\",{field.MinLength},{field.MaxLength}");
                        }
                        Environment.ExitCode = 0;
                    } catch (Exception ex) {
                        System.Console.Error.WriteLine(ex.Message);
                        Environment.ExitCode = 1;
                    }
                }
            }
            else
            {
                System.Console.Error.WriteLine(options.GetUsage());
                Environment.ExitCode = 1;
            }
        }
Пример #2
0
        /// <summary>
        /// The boot strapper start.
        /// </summary>
        private void BootStrapperStart()
        {
            // var bootstrapper = new UnityBootstrapper();
            var bootstrapper = new AutofacBootstrapper();

            bootstrapper.DoStart();
        }
Пример #3
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.ConfigureCors(
                options => options.AddPolicy(
                    _aureliaAppPolicyName,
                    builder =>
            {
                builder.WithOrigins(_appSettings.CorsOrigins);
                builder.AllowAnyMethod();
                builder.AllowAnyHeader();
            }));

            services.AddMvcCore(options => options.Filters.Add(new ExceptionFilter()))
            .AddJsonFormatters(serializerSettings =>
            {
                serializerSettings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
                serializerSettings.NullValueHandling = NullValueHandling.Ignore;
            })

                                #warning Related to: https://github.com/aspnet/Mvc/issues/3094, remove after beta 8 released.
            .AddViews();

            services.AddInstance(_configuration);
            services.AddInstance(_appSettings);

            IContainer container = AutofacBootstrapper.CreateContainer(
                services,
                Assembly.GetExecutingAssembly(),
                typeof(IBusManager).Assembly,
                typeof(ContextMiddleware).Assembly);

            return(container.Resolve <IServiceProvider>());
        }
Пример #4
0
        public void TestExporter()
        {
            var file = Path.GetTempFileName();

            File.WriteAllText(file, @"t1,t2,t3,t4
Monday,10,1.1,1/1/2014
Tuesday,11,2.2,2/1/2014
Wednesday,12,3.3,3/1/2014
Wednesday,12,3.3,3/1/2014
Thursday,13,4.4,4/1/2014
Friday,14,5.5,5/1/2014
Saturday,15,6.6,6/1/2014");

            File.Delete(Output);

            var connection = new Connection {
                Name = "input", Provider = "file", File = file
            };

            using (var scope = new AutofacBootstrapper(connection)) {
                var result  = scope.Resolve <IImporter>().Import(connection);
                var profile = scope.Resolve <IProfiler>().Profile(result, 30);
                var builder = new StringBuilder();
                builder.AppendLine("Name,Type,Position,Count,Min Value,Max Value,Min Length,Max Length");
                foreach (var field in profile)
                {
                    builder.AppendLine($"{field.Field.Name},{field.Field.Type},{field.Field.Index},{field.Count},\"{field.MinValue}\",\"{field.MaxValue}\",{field.MinLength},{field.MaxLength}");
                }
                File.WriteAllText(Output, builder.ToString());
            }

            Assert.IsTrue(File.Exists(Output));
        }
Пример #5
0
        public void ExceptionWithoutHandlerThrowsException()
        {
            var bootstrapper = new AutofacBootstrapper()
                               .WithContainer(new ExceptionThrowingContainerConfiguration());

            Assert.Throws <NotImplementedException>(() => bootstrapper.Build());
        }
Пример #6
0
 protected void Application_Start()
 {
     AutofacBootstrapper.Run();
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
 }
Пример #7
0
 static void Main(string[] args)
 {
     using (var container = AutofacBootstrapper.Bootstrap())
     {
         var example = container.Resolve <DependencyInjectionExample>();
         example.Show();
     }
 }
Пример #8
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     DependencyResolver.SetResolver(new AutofacDependencyResolver(AutofacBootstrapper.Configure().Build()));
 }
        public void Should_be_able_to_create_service_locator()
        {
            var buildManager = new Mock<IBuildManager>();
            buildManager.SetupGet(bm => bm.Assemblies).Returns(new[] { GetType().Assembly });

            var bootstrapper = new AutofacBootstrapper(buildManager.Object);

            Assert.IsType<AutofacAdapter>(bootstrapper.ServiceLocator);
        }
Пример #10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Platform.Init(this, savedInstanceState);
            Forms.Init(this, savedInstanceState);
            AutofacBootstrapper.RegisterAutofacModules();

            this.LoadApplication(AutofacBootstrapper.Instance.Resolve <App>());
        }
Пример #11
0
        public MainPage()
        {
            InitializeComponent();

            var container = AutofacBootstrapper.Start();
            var viewModel = container.Resolve <HipsterViewModel>();

            DataContext = viewModel;
            ViewModel   = viewModel;
        }
Пример #12
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Autofac
            AutofacBootstrapper.Run();
        }
Пример #13
0
        public void ExceptionWhenHandledReturnsNullHost()
        {
            var host = new AutofacBootstrapper()
                       .WithContainer(new ExceptionThrowingContainerConfiguration())
                       .WithExceptionHandler((exception, loggerFactory) => true)
                       .Configure()
                       .Build();

            Assert.Null(host);
        }
Пример #14
0
        public void Should_be_able_to_create_adapter()
        {
            var buildManager = new Mock<IBuildManager>();
            var bootStrapperTaskRegistery = new Mock<IBootstrapperTasksRegistry>();
            var perRequestTaskRegistery = new Mock<IPerRequestTasksRegistry>();
            buildManager.SetupGet(bm => bm.Assemblies).Returns(new[] { GetType().Assembly });

            var bootstrapper = new AutofacBootstrapper(buildManager.Object, bootStrapperTaskRegistery.Object, perRequestTaskRegistery.Object);

            Assert.IsType<AutofacAdapter>(bootstrapper.Adapter);
        }
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var container = AutofacBootstrapper.Execute();

            return(new HostBuilder()
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .ConfigureHostConfiguration(ConfigureHost(args))
                   .ConfigureAppConfiguration(ConfigureApplicationConfig())
                   .UseServiceProviderFactory(new AutofacChildLifetimeScopeServiceProviderFactory(container))
                   .ConfigureWebHostDefaults(ConfigureWebHost())
                   .ConfigureLogging(ConfigureLogging()));
        }
Пример #16
0
        /// <summary>
        /// Gets the web host builder.
        /// </summary>
        /// <returns>The web host builder.</returns>
        public async Task <IWebHostBuilder> GetWebHostBuilder()
        {
            var taskResolver = await this.GetAdditionalConfigurationTaskResolver();

            var hostBuilder = new AutofacBootstrapper()
                              .WithTasks(taskResolver)
                              .WithContainer(new CompositeContainerConfiguration(this.currentContainerConfiguration, this.dictionaryConfiguration))
                              .WithAppBuilderConfigurations(this.appBuilderConfigurations)
                              .Configure();

            return(this.Configure(hostBuilder));
        }
Пример #17
0
        public void ExceptionWithHandlerPassesLoggerFactory()
        {
            var bootstrapper = new AutofacBootstrapper()
                               .WithContainer(new ExceptionThrowingContainerConfiguration())
                               .WithExceptionHandler((exception, loggerFactory) =>
            {
                Assert.NotNull(loggerFactory);
                return(true);
            });

            bootstrapper.Build();
        }
Пример #18
0
        public static IContainer Initialize()
        {
            var configuration = new ConfigurationService();

            var builder = new ContainerBuilder();

            builder.Register(c => configuration).As <ConfigurationService>().SingleInstance();
            builder.Register(c => configuration.CurrentConfiguration).As <IAppConfiguration>().SingleInstance();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();

            return(AutofacBootstrapper.Initialize(new ContainerBuilder()));
        }
Пример #19
0
        public App()
        {
            this.InitializeComponent();

            this._bootstrapper = new AutofacBootstrapper();

            /* bootstrapper.Initialize() needs to be placed here because CM's bootstrapper internally subscribes to:
             * Application.Startup
             * Application.DispatcherUnhandledException
             * Application.Exit += OnExit
             */
            this._bootstrapper.Initialize();
        }
Пример #20
0
        // [Ignore("Depends on NorthWind database on local SQL Server.")]
        public void TestProfilerDatabase()
        {
            var connection = new Connection {
                Name = "input", Provider = "sqlserver", Database = "Northwind", Table = "Customers"
            };

            using (var scope = new AutofacBootstrapper(connection)) {
                var result  = scope.Resolve <IImporter>().Import(connection);
                var profile = scope.Resolve <IProfiler>().Profile(result, 30);
                Assert.NotNull(result);
                Assert.NotNull(profile);
            }
        }
Пример #21
0
        public void Configuration(IAppBuilder app)
        {
            var configurationService = new ConfigurationService();
            var config = new HttpConfiguration();

#if DEBUG
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Debug()
                         .CreateLogger();

            config.Services.Add(typeof(IExceptionLogger), new DebugExceptionLogger());
#else
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Elmah()
                         .CreateLogger();
#endif
            // Autofac
            var builder = new ContainerBuilder();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => Log.Logger).As <ILogger>().SingleInstance();
            builder.RegisterType <ElmahSqlLogger>().AsSelf().InstancePerRequest();

            var container = AutofacBootstrapper.Initialize(builder, config, configurationService);

            // Web API
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
            config.Filters.Add(new ElmahHandleErrorApiAttribute());
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver {
                IgnoreSerializableAttribute = true
            };

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = configurationService.CurrentConfiguration.SiteRoot,
                RequiredScopes = new[] { "api2" },
                ValidationMode = ValidationMode.ValidationEndpoint
            });

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);

            config.Formatters.Add(new BsonMediaTypeFormatter());

            app.UseWebApi(config);

            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        }
Пример #22
0
        public void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();

            AutomapperConfig.Initialize();
            AutofacBootstrapper.Run();

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            ConfigureAuth(app);
        }
Пример #23
0
        private static void Main(string[] args)
        {
            var container     = AutofacBootstrapper.Init();
            var plutusService = container.Resolve <IPlutusService>();
            var settings      = container.Resolve <ISettingsLoader>();

            _logger = container.Resolve <ILogger>();

            JobManager.Initialize(new PlutusRegistry(plutusService, settings));

            JobManager.JobException += HandleJobException;

            Console.ReadKey();
            JobManager.Stop();
        }
Пример #24
0
        public void Should_be_able_to_load_modules()
        {
            var buildManager = new Mock<IBuildManager>();
            var bootStrapperTaskRegistery = new Mock<IBootstrapperTasksRegistry>();
            var perRequestTaskRegistery = new Mock<IPerRequestTasksRegistry>();
            buildManager.SetupGet(bm => bm.ConcreteTypes).Returns(new[] { typeof(DummyModule) });

            DummyModule.Configured = false;

            var bootstrapper = new AutofacBootstrapper(buildManager.Object, bootStrapperTaskRegistery.Object, perRequestTaskRegistery.Object);

            Assert.NotNull(bootstrapper.Adapter);

            Assert.True(DummyModule.Configured);
        }
Пример #25
0
        public static Task EnsureBootstrapped()
        {
            if (!_isInitialized)
            {
                lock (_lockObject)
                {
                    if (!_isInitialized)
                    {
                        AutofacBootstrapper.Initialize();
                        _isInitialized = true;
                    }
                }
            }

            return(Task.CompletedTask);
        }
Пример #26
0
        protected override Task BeforeAsync()
        {
            if (!_isInitialized)
            {
                Environment.SetEnvironmentVariable("KEKIRI_OUTPUT", "console,files");
                lock (_lockObject)
                {
                    if (!_isInitialized)
                    {
                        AutofacBootstrapper.Initialize();
                        _isInitialized = true;
                    }
                }
            }

            return(Task.CompletedTask);
        }
        public static void Initiate()
        {
            var a = Assembly.GetCallingAssembly().GetReferencedAssemblies();
            var referencedProjectAssemblyNames =
                Assembly
                .GetCallingAssembly()
                .GetReferencedAssemblies()
                .Where(assembly => assembly.Name.StartsWith("NetCoreConsoleDemo"))
                .ToList();
            var assemblies = referencedProjectAssemblyNames
                             .Select(assemblyName => Assembly.Load(assemblyName))
                             .ToArray();

            var bootstrapper = new AutofacBootstrapper();

            _container = bootstrapper.InitiateAutofacContainerBuilder(assemblies);
        }
Пример #28
0
        static void InternalMain(string[] args)
        {
            if (args.Length != 2)
            {
                WriteUsage();
                return;
            }

            var inputPath  = args[0].ToApplicationRelativeAbsolutePath();
            var outputPath = args[1].ToApplicationRelativeAbsolutePath();

            using (var bootstrapper = new AutofacBootstrapper())
            {
                var context = bootstrapper.GetContext();

                var directoryService     = context.Resolve <IDirectoryService>();
                var metaDataFactory      = context.Resolve <IMetaDataFactory>();
                var audioFileService     = context.Resolve <IAudioFileService>();
                var metaDataQueueFactory = context.Resolve <IMetaDataQueueFactory>();

                // Create input path traverser and replicate the input directory
                // structure into the output directory.
                var inputPathTraverser = directoryService.Traverse(inputPath);
                directoryService.PrepareReplication(inputPath, outputPath).Replicate();

                // Create metadata for each .m4a file in the input directory.
                var inputMetaData = inputPathTraverser
                                    .SelectMany(di => di.GetFiles("*.m4a"))
                                    .Select(f => metaDataFactory.Create(inputPath, f.FullName, outputPath))
                                    .ToArray();

                // Create the metadata queue.
                var metaDataQueue = metaDataQueueFactory.Create(inputMetaData);

                // Run conversion.
                Task.WaitAll(
                    ConvertRoutine(audioFileService, metaDataQueue),
                    ConvertRoutine(audioFileService, metaDataQueue),
                    ConvertRoutine(audioFileService, metaDataQueue),
                    ConvertRoutine(audioFileService, metaDataQueue)
                    );

                Console.WriteLine("Conversion has been completed.");
            }
        }
Пример #29
0
        protected override void OnStartup(StartupEventArgs e)
        {
            ContainerBuilder builder = new ContainerBuilder();

            AutofacBootstrapper.RegisterType(builder);
            this.Container = builder.Build();

            using (ILifetimeScope lifeTimeScope = this.Container.BeginLifetimeScope())
            {
                ILoggerFactory loggerFactory = lifeTimeScope.Resolve <ILoggerFactory>();
                loggerFactory.AddNLog(new NLogProviderOptions
                {
                    CaptureMessageTemplates  = true,
                    CaptureMessageProperties = true
                });

                IMainWindow mainWindow = lifeTimeScope.Resolve <IMainWindow>();
                mainWindow.ShowDialog();
            }
        }
Пример #30
0
        static void InternalMain(string[] args)
        {
            if (args.Length != 2)
            {
                WriteUsage();
                return;
            }

            var inputPath  = args[0].ToApplicationRelativeAbsolutePath();
            var outputPath = args[1].ToApplicationRelativeAbsolutePath();

            using (var bootstrapper = new AutofacBootstrapper())
            {
                var context = bootstrapper.GetContext();

                var directoryService = context.Resolve <IDirectoryService>();
                var pathTransformer  = context.Resolve <IPathTransformer>();

                // Create input path traverser and replicate the input directory
                // structure into the output directory.
                var inputPathTraverser = directoryService.Traverse(inputPath);

                var shortcutEmbryos = inputPathTraverser
                                      .SelectMany(di => di
                                                  .GetFiles("*.mp3")
                                                  .Select(fi => new ShortcutEmbryo(pathTransformer, fi, inputPath, outputPath))
                                                  )
                                      .ToArray();

                foreach (var embryo in shortcutEmbryos)
                {
                    Console.WriteLine();
                    Console.WriteLine("Input file: {0}", embryo.FileInfo.FullName);
                    Console.WriteLine("Output shortcut: {0}", embryo.OutputFilePath);
                    CreateShortcut(embryo.OutputName, embryo.OutputFilePath, embryo.FileInfo.FullName);
                }

                Console.WriteLine("Shortcuts have been created.");
            }
        }
Пример #31
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region [MVC Register]

            //services.Configure<CookiePolicyOptions>(options =>
            //    {
            //        options.CheckConsentNeeded = context => true;
            //        options.MinimumSameSitePolicy = SameSiteMode.None;
            //    });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddScoped <IViewRenderService, ViewRenderService>();

            services.AddSession();

            #endregion [MVC Register]


            #region [Configuration Register]

            var configuration = new ConfigurationHelper();
            Configuration.Bind("Configuration", configuration);
            services.AddSingleton(configuration);

            #endregion [Configuration Register]

            #region [Autofac]

            var builder = new ContainerBuilder();

            builder.Populate(services);
            AutofacBootstrapper.BuilderContainer(builder);
            this.ApplicationContainer = AutofacBootstrapper.GetContainer();

            return(new AutofacServiceProvider(this.ApplicationContainer));

            #endregion [Autofac]
        }
        public CreateOrdineClienteTest()
        {
            var builder = AutofacBootstrapper.BuilderContainer();

            this._container = builder.Build();
        }
        public CreateArticoloTest()
        {
            var builder = AutofacBootstrapper.BuilderContainer();

            this._container = builder.Build();
        }