Skip to content

Instantly share code, notes, and snippets.

@JeffryGonzalez
Created July 7, 2020 22:18
Show Gist options
  • Save JeffryGonzalez/f7fe5327f1efb4927c2d3ef9351c7761 to your computer and use it in GitHub Desktop.
Save JeffryGonzalez/f7fe5327f1efb4927c2d3ef9351c7761 to your computer and use it in GitHub Desktop.
public class CustomWebApplicationFactory<TStartup> :
WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
foreach(var kvp in deps)
{
var descriptor = services.SingleOrDefault(d =>
d.ServiceType == kvp.Key
);
if(descriptor != null)
{
services.Remove(descriptor);
}
services.AddSingleton(kvp.Key, kvp.Value);
}
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
HandleScopedServices(scope);
});
}
protected virtual void HandleScopedServices(IServiceScope scope)
{
}
protected Dictionary<Type, object> deps = new Dictionary<Type, object>();
protected void AddTestDouble<TService>(TService dep)
{
deps.Add(typeof(TService), dep);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment