The repository is available here: https://github.com/ranouf/TestingWithDotNetCore3_0/tree/WithDatabase
I'm looking for a way to upgrade from .Net Core 2.0 to 3.0 my Integration Tests. I really try my best to be able to inject a damned service, as you can see, I tried every where I could:
var hostBuilder = new HostBuilder()
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddXunit(Output);
})
.ConfigureServices(services =>
{
services.AddAutofac();
services.AddSingleton<IMyService, MyService>(); //Here
})
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope();//Here
})
.ConfigureWebHost(webHost =>
{
// Add TestServer
webHost
.UseStartup<TestStartup>()
.UseTestServer()
.ConfigureServices(services =>
{
services.AddSingleton<IMyService, MyService>();//Here
services.AddAutofac();
services
.AddControllers()
.AddApplicationPart(typeof(TestStartup).Assembly);
})
.ConfigureTestServices(services =>
{
services.AddSingleton<IMyService, MyService>();//Here
services.AddAutofac();
services
.AddControllers()
.AddApplicationPart(typeof(TestStartup).Assembly);
})
.ConfigureTestContainer<ContainerBuilder>(builder =>
{
builder.RegisterType<MyService>().As<IMyService>().InstancePerLifetimeScope();//Here
});
});
But guess what? It doesnt work at all ... I really don't know how I can make the HostBuilder understand ... Of course I tried to alternativaly keep only one way to inject my service
So when I want to get the Service:
Host = hostBuilder.Start();
Server = Host.GetTestServer();
Client = Host.GetTestClient();
using (var scope = Host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var myService = services.GetRequiredService<MyService>();
}
catch (Exception ex)
{
Output.WriteLine("HOST: " + ex.Message);
}
}
using (var scope = Server.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var myService = services.GetRequiredService<MyService>();
}
catch (Exception ex)
{
Output.WriteLine("SERVER: " + ex.Message);
}
}
The error message is:
The requested service 'MyAPI.Services.MyService' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
How do you succeed to inject a service in HostBuilder?
Aucun commentaire:
Enregistrer un commentaire