网络核心:从Microsoft.AspNetCore.Hosting.IWebHostBuilder转换为“ Microsoft.AspNetCore.Hosting.IWebHost”

时间:2019-08-02 20:02:54

标签: c# asp.net-core .net-core xunit

如何将IWebHostBuilder转换为IWebHost?我正在引用此代码,并在下面出现错误:是否有简单的方法来强制转换?当前试图最终在Xunit中将启动与集成测试一起使用。

  

无法从Microsoft.AspNetCore.Hosting.IWebHostBuilder转换为   “ Microsoft.AspNetCore.Hosting.IWebHost”

    public class DependencyResolverHelpercs
    {
        private readonly IWebHost _webHost;

        /// <inheritdoc />
        public DependencyResolverHelpercs(IWebHost WebHost) => _webHost = WebHost;

        public T GetService<T>()
        {
            using (var serviceScope = _webHost.Services.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
                try
                {
                    var scopedService = services.GetRequiredService<T>();
                    return scopedService;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            };
        }
    }
}

        var webHost = new WebHostBuilder()
            .UseContentRoot("C:\\APITest\\APITest.WebAPI")
            .UseEnvironment("Development")
            .UseConfiguration(new ConfigurationBuilder()
                .SetBasePath("C:\\APITest\\APITest.WebAPI)
                .AddJsonFile("appsettings.json")
                .Build())
                .UseStartup<Startup>();

        _serviceProvider = new DependencyResolverHelpercs(webHost);

1 个答案:

答案 0 :(得分:2)

您应该可以调用Build() method on WebHostBuilder来获取IWebHost的实例:

    var webHost = new WebHostBuilder()
        .UseContentRoot("C:\\APITest\\APITest.WebAPI")
        .UseEnvironment("Development")
        .UseConfiguration(new ConfigurationBuilder()
            .SetBasePath("C:\\APITest\\APITest.WebAPI)
            .AddJsonFile("appsettings.json")
            .Build())
        .UseStartup<Startup>()
        .Build();