C# 跑,;在Visual Studio 2017中共享用于测试的单个服务器实例

C# 跑,;在Visual Studio 2017中共享用于测试的单个服务器实例,c#,.net,unit-testing,mstest,visual-studio-2017,C#,.net,Unit Testing,Mstest,Visual Studio 2017,我的Visual Studio 2017项目包含几个单元测试项目。所有这些测试都在单个ASP.NET核心服务器上运行。我想在所有测试之前启动一次ASP.NET核心服务器,并在所有测试之后关闭它 我的主测试项目包含一个用于启动测试服务器的类: public class TestServer : IDisposable { public static string Url { get { return "http://localhost:44391/"; } } private stati

我的Visual Studio 2017项目包含几个单元测试项目。所有这些测试都在单个ASP.NET核心服务器上运行。我想在所有测试之前启动一次ASP.NET核心服务器,并在所有测试之后关闭它

我的主测试项目包含一个用于启动测试服务器的类:

public class TestServer : IDisposable
{
  public static string Url { get { return "http://localhost:44391/"; } }

  private static string GetApplicationPath()
  {
    return Path.GetFullPath(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "..", "..", "..", "..", "..", "..", "src", "MyProject"));
  }

  public IWebHost BuildHost()
  {
    var config = new ConfigurationBuilder()
        .AddEnvironmentVariables(prefix: "ASPNETCORE_")
        .Build();

    var host = new WebHostBuilder()
        .UseConfiguration(config)
        .UseEnvironment("UnitTests")
        .UseKestrel()
        .UseUrls(TestServer.Url)
        .UseContentRoot(GetApplicationPath())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();
    return host;
  }


  private IWebHost _testserver;
  public TestServer()
  {
    _testserver = BuildHost();
    _testserver.Start();
  }

  #region IDisposable

  ~TestServer()
  {
    Dispose(false);
  }

  public void Dispose()
  {
    Dispose(true);
    GC.SuppressFinalize(this);
  }

  bool _IsDisposed = false;

  protected virtual void Dispose(bool disposeManagedResources)
  {
    if (this._IsDisposed)
      return;
    if (disposeManagedResources)
    {
      _testserver.Dispose();
    }
    this._IsDisposed = true;
  }
  #endregion
}
这对于我的主测试组件非常有效。但是,如果我添加另一个带有测试的程序集,其中包含TestServerFixture for assembly Init和Cleanup,它们将不会共享该服务。相反,VisualStudio测试将尝试启动该服务两次

我猜每个包含测试的项目/程序集都是在一个单独的应用程序域中启动的

如何在多个测试程序集之间共享静态服务器/服务

public static class TestServerStaticHelper
{
  static object LockServer = new object();
  static int ServerCount = 0;
  static TestServer _service;
  public static void Attach()
  {
    lock (LockServer)
    {
      ServerCount++;
      if (_service == null)
        _service = new TestServer();
    }
  }
  public static void Detach()
  {
    lock (LockServer)
    {
      ServerCount--;
      if (ServerCount <= 0 && _service != null)
      {
        _service.Dispose();
        _service = null;
      }
    }
  }
}
[TestClass]
public class TestServerFixture
{
  [AssemblyInitialize()]
  public static void AssemblyInit(TestContext context)
  {
    TestServerStaticHelper.Attach();
  }

  [AssemblyCleanup()]
  public static void AssemblyCleanup()
  {
    TestServerStaticHelper.Detach();
  }
}