如何解决在集成测试期间从 HostingStartup 获取服务集合
我正在编写集成测试并遇到一个问题,因此无法获取所有服务的集合。
我有一个继承自 IHostingStartup 的 HostingInitialization 类。我需要获取在那里创建的整个服务集合。
我的 HostingInitialization 类:
[assembly: HostingStartup(typeof(MyProject.Bootstrap.HostingInitialization))]
namespace MyProject.Bootstrap
{
public class HostingInitialization : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context,services) =>
{
services.Configure<MongoOptions>(context.Configuration.GetSection(MongoOptions.JsonKey));
services.AddHttpContextAccessor();
});
}
}
}
我的测试课:
[SetUpFixture]
public class Testing
{
private static IConfigurationRoot _configuration;
private static IServiceScopeFactory _scopeFactory;
private static IWebHostEnvironment _webHostEnvironment;
[OneTimeSetUp]
public void RunBeforeAnyTests()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsetting.json",true,true)
.AddEnvironmentVariables();
_configuration = builder.Build();
_webHostEnvironment = Mock.Of<IWebHostEnvironment>(h => h.EnvironmentName == "Production");
var startup = new Startup(_webHostEnvironment,_configuration);
var services = new ServiceCollection();
services.AddSingleton(Mock.Of<IWebHostEnvironment>(w =>
w.EnvironmentName == "Production" &&
w.ApplicationName == "MyProject.Api"));
services.AddLogging();
startup.ConfigureServices(services);
_scopeFactory = services.BuildServiceProvider().GetService<IServiceScopeFactory>();
}
public static async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
{
using var scope = _scopeFactory.CreateScope();
var mediator = scope.ServiceProvider.GetService<IMediator>();
return await mediator.Send(request);
}
}
如何获得所有服务的完整集合?目前,我仅使用 Startup 类中的 ConfigureServices 方法获取服务集合。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。