/// <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); }
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> /// /// </summary> /// <param name="builder"></param> /// <param name="jsonConfigFiles"></param> /// <returns></returns> public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseJsonFileConfig(this Microsoft.AspNetCore.Hosting.IWebHostBuilder builder, Func <Microsoft.AspNetCore.Hosting.WebHostBuilderContext, IEnumerable <FileInfo> > jsonConfigFiles = null) { if (jsonConfigFiles == null) { return(builder); } //config builder builder.ConfigureAppConfiguration((h, g) => { var files = jsonConfigFiles?.Invoke(h); if (files.IsNotNullOrEmpty()) { foreach (var file in files) { if (file.Exists) { g.AddConfiguration(new ConfigurationBuilder().SetBasePath(h.HostingEnvironment.ContentRootPath).AddJsonFile(file.FullName, true, true).Build()); } else { throw new System.IO.FileNotFoundException(string.Format("找不到文件{0}", file.FullName)); } } } //if (File.Exists(Path.Combine(h.HostingEnvironment.ContentRootPath, "appsettings.json"))) // g.AddConfiguration(new ConfigurationBuilder().SetBasePath(h.HostingEnvironment.ContentRootPath).AddJsonFile("appsettings.json", true, true).Build()); //if (File.Exists(Path.Combine(h.HostingEnvironment.ContentRootPath, $"appsettings.{h.HostingEnvironment.EnvironmentName}.json"))) // g.AddConfiguration(new ConfigurationBuilder().SetBasePath(h.HostingEnvironment.ContentRootPath).AddJsonFile($"appsettings.{h.HostingEnvironment.EnvironmentName}.json", true, true).Build()); }); return(builder); }
protected override TestServer CreateServer(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) { var server = base.CreateServer(builder); server.AllowSynchronousIO = true; return(server); }
protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) { builder.ConfigureTestServices(services => { // Adiciona um novo service provider para os testes var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // IMPORTANTE: No .net Core 3.0 e acima, o InMemory do DbContext não está funcionando no ServiceProvider. // Para contornar este problema, pesquisando na Web encontrei este Workaround: https://stackoverflow.com/questions/58375527/override-ef-core-dbcontext-in-asp-net-core-webapplicationfactory // O qual implementei abaixo: // Remove the app's ApplicationDbContext registration. var descriptor = services.SingleOrDefault( d => d.ServiceType == typeof(DbContextOptions <MovieStoreDbContext>)); if (descriptor != null) { services.Remove(descriptor); } // Add ApplicationDbContext using an in-memory database for testing. services.AddDbContext <MovieStoreDbContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); // Compilando o Service Provider var sp = services.BuildServiceProvider(); // Criando o escopo para obter a referência do contexto da base de dados using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var movieStoreDb = scopedServices.GetRequiredService <MovieStoreDbContext>(); var logger = scopedServices.GetRequiredService <ILogger <WebApplicationFactory <Startup> > >(); // Cria a base de dados movieStoreDb.Database.EnsureCreated(); try { // Popula a base de dados para testes SeedData.PopulateTestData(movieStoreDb); } catch (Exception ex) { logger.LogError(ex, $"Ocorreu um erro ao popular a base de dados para testes. Erro: {ex.Message}"); } } }); }
/// <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) => /// WebHost.CreateDefaultBuilder(args) /// .UseSerilog() /// .UseStartup<Startup>(); /// </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); }
public static IHostBuilder AddApollo(this IHostBuilder hostBuilder, string appId, string metaServer) { if (appId == null) { throw new ArgumentNullException(nameof(appId)); } if (metaServer == null) { throw new ArgumentNullException(nameof(metaServer)); } return(hostBuilder.ConfigureAppConfiguration((_, builder) => builder.AddApollo(appId, metaServer))); }
public static IHostBuilder AddApollo(this IHostBuilder hostBuilder, Action <ApolloOptions> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var options = new ApolloOptions(); configure(options); return(hostBuilder.ConfigureAppConfiguration((_, builder) => builder.AddApollo(options))); }
/// <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) => /// WebHost.CreateDefaultBuilder(args) /// .UseSerilogExternallyRegistered() /// .UseStartup<Startup>(); /// </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); }
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}"); } } }); }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseUrls(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, params string[] urls) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, string startupAssemblyName) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder Configure(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action <Microsoft.AspNetCore.Builder.IApplicationBuilder> configureApp) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Type startupType) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureLogging(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action <Microsoft.Extensions.Logging.ILoggingBuilder> configureLogging) { throw null; }
public void Configure(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) { }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseSockets(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseWebRoot(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, string webRoot) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseSockets(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action <Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.SocketTransportOptions> configureOptions) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder PreferHostingUrls(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, bool preferHostingUrls) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseIISIntegration(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder SuppressStatusMessages(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, bool suppressStatusMessages) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStaticWebAssets(this Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseConfiguration(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, Microsoft.Extensions.Configuration.IConfiguration configuration) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseDefaultServiceProvider(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action <Microsoft.Extensions.DependencyInjection.ServiceProviderOptions> configure) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseEnvironment(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, string environment) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseStartup <TStartup>(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder) where TStartup : class { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseServer(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, Microsoft.AspNetCore.Hosting.Server.IServer server) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder ConfigureAppConfiguration(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.Action <Microsoft.Extensions.Configuration.IConfigurationBuilder> configureDelegate) { throw null; }
public static Microsoft.AspNetCore.Hosting.IWebHostBuilder UseShutdownTimeout(this Microsoft.AspNetCore.Hosting.IWebHostBuilder hostBuilder, System.TimeSpan timeout) { throw null; }