我正在使用 AspNetCore 2.2
遵循(更多)此处的文档:https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2 https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2
我正在使用 Autofac,我的 Startup 类具有以下方法:
public void ConfigureServices(IServiceCollection services)
public void ConfigureContainer(ContainerBuilder containerBuilder) //this is where things can be registered directly with autofac and runs after ConfigureServices
public void Configure(...) //the method called by runtime
我使用 Autofac 的方式,正如其文档所推荐的那样,是通过Program.cs like this
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.ConfigureServices(services => services.AddAutofac())
.UseIISIntegration()
.UseStartup<Startup>()
.ConfigureAppConfiguration((builderContext, config) =>
{
var env = builderContext.HostingEnvironment;
config
.AddJsonFile("appsettings.json", false, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
.AddEnvironmentVariables();
});
}
我现在正在使用 TestServer 进行我的测试项目,我想在其中使用真正的 Startup 类。但我想修改其中一个依赖项。
我看到有一个方法可用WebHostBuilder
to .ConfigureTestServices(services => {});
所以我尝试了以下方法:
public abstract class ComponentTestFeature
: Feature
{
protected HttpClient HttpClient { get; }
protected ComponentTestFeature()
{
var configuration =
new ConfigurationBuilder()
.AddJsonFile("appsettings.Test.json")
.Build();
var webHostBuilder =
new WebHostBuilder()
.ConfigureServices(services => services.AddAutofac())
.ConfigureTestServices(services =>
{
services.AddScoped<IEventStoreManager, MockEventStoreManager>();
})
.UseConfiguration(configuration)
.UseStartup<Startup>();
var server = new TestServer(webHostBuilder);
HttpClient = server.CreateClient();
var myService = server.Host.Services.GetRequiredService<IEventStoreManager>();
}
}
正如你所看到的,我想使用MockEventStoreManager
实施IEventStoreManager
所以这是应该由容器解决的实现。然而,这并没有按预期工作,并且 myServiceresolved 是原始实现,真正的实现,而不是模拟的实现。
有谁知道我怎样才能实现我想要的?
更新1:
经过更多调查后,我不得不在 github AspNetCore 上创建一个问题,因为扩展方法是在 ConfigureContainer 之前执行的,因此我无法真正覆盖 autofac 依赖项,也无法稍后检索 autofac 容器。https://github.com/aspnet/AspNetCore/issues/6522 https://github.com/aspnet/AspNetCore/issues/6522
更新2:
仅供参考,这就是 Startup.cs 的样子。可以看到除了mvc之外的所有依赖都注册在autofac的容器中。
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This is where things can be registered directly with autofac and runs after ConfigureServices, so it will override it
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<EventStoreManager>().As<IEventStoreManager>();
}
我想做的是使用MockEventStoreManager
实施IEventStoreManager
在我的测试中,所以我需要以一种很好的方式覆盖(从我的测试项目)Autofac 的注册。