WebApplicationFactory中.NET Core 2.1和3.1之间对ConfigureServices的调用顺序不同

问题描述 投票:0回答:1

在从.NET Core 2迁移到3的过程中,我注意到WebApplicationFactory发生了重大变化。复制:https://github.com/lukasz-pyrzyk/orderofconfigureservices

在用于集成测试的基础库中,我使用WebApplicationFactory来设置服务器和配置服务。例如,假设以下服务


    public interface IHelloService
    {
        string Say();
    }

    public class HelloService : IHelloService
    {
        public string Say() => "Hello from original service";
    }

    public class CustomHelloService : IHelloService
    {
        public string Say() => "Hello from custom service";
    }

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.TryAddSingleton<IHelloService, HelloService>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
        }
    }


集成测试的基类,灯具看起来如下

    public class TestFixture : IntegrationTests<Startup>
    {
        [Fact]
        public void SayHallo()
        {
            var service = Services.GetService<IHelloService>();
            Assert.Equal("Hello from custom service", service.Say());
        }

        protected override void ConfigureServices(IServiceCollection services)
        {
            services.TryAddSingleton<IHelloService, CustomHelloService>();
        }
    }


    public abstract class IntegrationTests<TStartup> : IDisposable where TStartup : class
    {
        private readonly WebApplicationFactory<TStartup> _factory;

        protected IntegrationTests() : this(typeof(TStartup).Assembly.GetName().Name)
        {
        }

        protected IntegrationTests(string projectRelativePath)
        {
            _factory = new WebApplicationFactory<TStartup>().WithWebHostBuilder(b =>
            {
                b
                    .UseSolutionRelativeContentRoot(Path.Combine("src", projectRelativePath))
                    .ConfigureServices(ConfigureServices);
            });

            _factory.CreateClient();
            Services = _factory.Services;
        }

        protected IServiceProvider Services { get; }

        protected virtual void ConfigureServices(IServiceCollection services)
        {
        }

        public void Dispose()
        {
            _factory.Dispose();
        }
    }

.NET Core 2.1Microsoft.AspNetCore.Mvc.Testing 2.1.3上的方法TestFixture.ConfigureServices()被称为之前 Startup.ConfigureServices测试通过

.NET Core 3.1Microsoft.AspNetCore.Mvc.Testing 3.1.1上,方法TestFixture.ConfigureServices()被称为之后 Startup.ConfigureServices测试失败

您知道此更改是否是有意的吗?使用.NET Core 2.1,首先调用来自test的ConfigureServices,并且TryAddSingleton正在注册我的模拟服务。稍后,Startup.ConfigureServices跳过了注册,因为已经添加了服务。

使用.NET Core 3.1,我不得不调用AddSingleton来替换服务。是错误还是想要的更改?我可以以某种方式克服它吗?

c# asp.net .net core
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.