Search code examples
c#asp.net-coreocelot

'WebHost' is inaccessible due to its protection level


I am trying to follow Microsoft's Ocelot API Gateway tutorial (https://learn.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/implement-api-gateways-with-ocelot).

First I intialized a new empty ASP.NET Core web app:

dotnet new web

Then I installed the Ocelot dependencies (https://www.nuget.org/packages/Ocelot/):

dotnet add package Ocelot --version 17.0.0

Then I took the code from the tutorial:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using System.IO;

namespace MyApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args)
        {
            var builder = WebHost.CreateDefaultBuilder(args);

            builder.ConfigureServices(s => s.AddSingleton(builder))
                    .ConfigureAppConfiguration(
                          ic => ic.AddJsonFile(Path.Combine("configuration",
                                                            "configuration.json")))
                    .UseStartup<Startup>();
            var host = builder.Build();
            return host;
        }
    }
}

But then it complains that the WebHost class, called in BuildWebHost method, "is inaccessible due to its protection level". According to Microsoft (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.webhost), WebHost "provides convenience methods for creating instances of IWebHost and IWebHostBuilder with pre-configured defaults.", and looks like so:

public static class WebHost
...

Why does it complain that WebHost is inaccessible, when the class is in fact public? What am I missing here?


Solution

  • From the documentation, WebHost is in the namespace Microsoft.AspNetCore. But in your code, It hasn't the using to this namespace.

    In Visual Studio, you can try Go to definition on WebHost to discover where the type come.

    As sujested by @leiflundgren, as your code has the using Microsoft.AspNetCore.Hosting, then the compiler thinks you want use Microsoft.AspNetCore.Hosting.WebHost.

    https://github.com/dotnet/aspnetcore/blob/main/src/Hosting/Hosting/src/Internal/WebHost.cs

    namespace Microsoft.AspNetCore.Hosting;
    
    internal sealed partial class WebHost : IWebHost, IAsyncDisposable
    {
    ....
    }
    

    But this class has the scope internal, then it isn't exposed and can be used by your code. Hence the following error :

    WebHost is inaccessible due to its protection level.