/// <summary>Sets Serilog as the logging provider.</summary>
 /// <remarks>
 /// A <see cref="WebHostBuilderContext"/> is supplied so that configuration and hosting information can be used.
 /// The logger will be shut down when application services are disposed.
 /// </remarks>
 /// <param name="builder">The web host builder to configure.</param>
 /// <param name="configureLogger">The delegate for configuring the <see cref="LoggerConfiguration" /> that will be used to construct a <see cref="Logger" />.</param>
 /// <param name="preserveStaticLogger">Indicates whether to preserve the value of <see cref="Log.Logger"/>.</param>
 /// <returns>The web host builder.</returns>
 public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Action <WebHostBuilderContext, LoggerConfiguration> configureLogger, bool preserveStaticLogger = false)
 {
     if (builder == null)
     {
         throw new ArgumentNullException(nameof(builder));
     }
     if (configureLogger == null)
     {
         throw new ArgumentNullException(nameof(configureLogger));
     }
     builder.ConfigureServices((context, collection) =>
     {
         var loggerConfiguration = new LoggerConfiguration();
         configureLogger(context, loggerConfiguration);
         var logger = loggerConfiguration.CreateLogger();
         if (preserveStaticLogger)
         {
             collection.AddSingleton <ILoggerFactory>(services => new SerilogLoggerFactory(logger, true));
         }
         else
         {
             // Passing a `null` logger to `SerilogLoggerFactory` results in disposal via
             // `Log.CloseAndFlush()`, which additionally replaces the static logger with a no-op.
             Log.Logger = logger;
             collection.AddSingleton <ILoggerFactory>(services => new SerilogLoggerFactory(null, true));
         }
     });
     return(builder);
 }
Пример #2
0
        protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var descriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                    typeof(DbContextOptions <InventarioContext>));

                services.Remove(descriptor);

                services.AddDbContext <InventarioContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                });

                var sp = services.BuildServiceProvider();

                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <InventarioContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    db.Database.EnsureCreated();
                }
            });
        }
 /// <summary>
 /// Sets Serilog as the logging provider.
 /// </summary>
 /// <param name="builder">The web host builder to configure.</param>
 /// <param name="logger">The Serilog logger; if not supplied, the static <see cref="Log"/> will be used.</param>
 /// <param name="dispose">When true, dispose <paramref name="logger"/> when the framework disposes the provider. If the
 /// logger is not specified but <paramref name="dispose"/> is true, the <see cref="Log.CloseAndFlush()"/> method will be
 /// called on the static <see cref="Log"/> class instead.</param>
 /// <returns>The web host builder.</returns>
 /// <example>
 /// <code>
 /// public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
 ///     WebHost.CreateDefaultBuilder(args)
 ///         .UseSerilog()
 ///         .UseStartup&lt;Startup&gt;();
 /// </code>
 /// </example>
 public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, ILogger logger = null, bool dispose = false)
 {
     if (builder == null)
     {
         throw new ArgumentNullException(nameof(builder));
     }
     builder.ConfigureServices(collection =>
                               collection.AddSingleton <ILoggerFactory>(services => new SerilogLoggerFactory(logger, dispose)));
     return(builder);
 }
        /// <summary>
        /// Sets Serilog as the logging provider, using an already-registered <see cref="ILogger"/>.
        /// </summary>
        /// <param name="builder">The web host builder to configure.</param>
        /// <returns>The web host builder.</returns>
        /// <example>
        /// <code>
        /// public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
        ///     WebHost.CreateDefaultBuilder(args)
        ///         .UseSerilogExternallyRegistered()
        ///         .UseStartup&lt;Startup&gt;();
        /// </code>
        /// </example>
        public static IWebHostBuilder UseSerilogExternallyRegistered(this IWebHostBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            // This has to be singleton in order to support the ASP.NET Core framework attempting to resolve it in singleton scope, otherwise we would get
            // an exception with the message `Cannot consume scoped service from singleton` during application startup.
            builder.ConfigureServices(collection =>
                                      collection.AddSingleton <ILoggerFactory>(services => new SerilogLoggerFactory(services.GetRequiredService <ILogger>())));

            return(builder);
        }
        /// <summary>
        /// Adds a custom implementation of Autofac's <see cref="IServiceProviderFactory{TContainerBuilder}"/> to the <see cref="IServiceCollection"/>
        /// being built by <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IWebHostBuilder"/> instance being configured.</param>
        /// <param name="forEachModule">An optional action used to configure each <see cref="IModule"/> being added to the container.</param>
        /// <param name="configurationAction">An optional action used to configure the container.</param>
        /// <returns>The existing <see cref="IWebHostBuilder"/> instance.</returns>
        /// <typeparam name="TModulesProvider">The type of provider that can enumerate all of the Autofac modules to be registered.</typeparam>
        /// <example>
        /// <code>
        /// public static IWebHostBuilder CreateWebHostBuilder(string[] args) =&gt;
        ///     WebHost.CreateDefaultBuilder(args)
        ///         .UseAutofacWithModulesProvider&lt;MyAutofacModulesProvider&gt;()
        ///         .UseStartup&lt;Startup&gt;();
        /// </code>
        /// </example>
        public static IWebHostBuilder UseAutofacWithModulesProvider <TModulesProvider>(this IWebHostBuilder builder, Action <IModule> forEachModule = null, Action <ContainerBuilder> configurationAction = null)
            where TModulesProvider : IModulesProvider, new()
        {
            void ForEachModule(IModule module)
            {
                (module as IOverridableHttpScopeAutofacModule)?.SetHttpScope(Scope.PerLifetimeScope);
                forEachModule?.Invoke(module);
            }

#if NET472 || NETSTANDARD2_0
            return(builder.ConfigureServices(services => services.AddAutofacWithModulesProvider <TModulesProvider>(ForEachModule, configurationAction)));
#elif NETSTANDARD2_1 || NETCOREAPP3_0
            return(builder.UseServiceProviderFactory(new ModulesProviderBasedAutofacServiceProviderFactory <TModulesProvider>(ForEachModule, configurationAction)));
#endif
        }
Пример #6
0
        protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkInMemoryDatabase()
                                      .BuildServiceProvider();

                services.AddDbContext <CarsContext>(options =>
                {
                    options.UseInMemoryDatabase("CarsIntegrationTestingDb");
                    options.UseInternalServiceProvider(serviceProvider);
                });

                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database contexts
                using (var scope = sp.CreateScope())
                {
                    var scopedServices  = scope.ServiceProvider;
                    var testingDatabase = scopedServices.GetRequiredService <CarsContext>();

                    var logger = scopedServices.GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    // Ensure the database is created.
                    testingDatabase.Database.EnsureCreated();

                    try
                    {
                        InitialData.PopulateTestData(testingDatabase);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "An error occurred seeding the " +
                                        "database with test messages. Error: {ex.Message}");
                    }
                }
            });
        }