Search code examples
c#asp.netautofacwebapi

Can't access GlobalConfiguration.Configuration from .Net 5.0 WebApi


GlobalConfiguration.Configuration seems unavailable in a new ASP.NET Core WebApi project (.Net 5.0) .

Steps to reproduce:

  1. Create a new "ASP.NET Core Web Api" project. (Target framework: .NET 5.0, Lang: C#)
  2. Add this line anywhere to your code: var config = GlobalConfiguration.Configuration;

e.g. Add it to Startup.cs:

public Startup(IConfiguration configuration)
{
        var c = GlobalConfiguration.Configuration;    // this line was added
        Configuration = configuration;
}
  1. You'll need a package for System.Web.Http.GlobalConfiguration which seems the correspond with the Microsoft.AspNet.WebApi.WebHost Nuget package, so install it with:
Install-Package Microsoft.AspNet.WebApi.WebHost -Version 5.2.7
  1. Run the application, to see it fail at our new code line with the exception below:
System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'System.Web.Routing.RouteTable'
  from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
  Source=System.Web.Http.WebHost
  StackTrace:
   at System.Web.Http.GlobalConfiguration.<>c.<CreateConfiguration>b__11_0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.get_Value()
   at System.Web.Http.GlobalConfiguration.get_Configuration()
   at AspNetCore5._0.Program.Main(String[] args) in C:\work\AspNetCore5.0\Program.cs:line 17

What I am ultimately trying to achieve... is to use AutoFac as my dependency resolver (I got this working). But when I follow AutoFac's documentation on FilterProviders to created my own custom Filters (e.g. ModelValidationFilter, ResponseFilter, ExceptionFilter), it requires that I obtain GlobalConfiguration.Configuration. AutoFac documentation on obtaining GlobalConfiguration suggests that I obtain GlobalConfiguration.Configuration for 'standard IIS hosting' as follows:

var config = GlobalConfiguration.Configuration;

... but it clearly fails.

I'll appreciate any help or advice on this. Thanks!


Solution

  • ASP.NET Core is not the same thing as ASP.NET or ASP.NET WebAPI, and whilst many things such as controllers require only minor tweaks to port, configuration and routing are very different.

    Since your ultimate goal is to install AutoFac as the dependency resolver, try following AutoFac's documentation for ASP.NET Core.