Search code examples
c#asp.netwebformsunity-containerdotnet-httpclient

HttpClient injected with Unity error in Web Forms page - Type or namespace name 'HttpClient' does not exist in the namespace 'System.Net.Http'


I'm maintaining an old ASP.NET 4.8 Web Forms application and trying to inject HttpClient into a Page using Unity Container. My Global.asax.cs page looks thusly:

var container = this.AddUnity();
container.RegisterType<HttpClient>(new InjectionFactory(x => new HttpClient()));

(I've also tried registering it as a Singleton and a few other ways to register it, but that doesn't seem to be the issue.)

In the code behind on my page, I have the following code:

public partial class page : Page 
{
    [Dependency]
    private HttpClient _httpClient { get; }

    public page() { }

    public page(HttpClient client)
    {
        _httpClient = client;
    }
}

I have dependency injection working fine elsewhere, so I don't think it's Unity's fault. I also have HttpClient elsewhere on this page, so I'm using System.Net.Http; it's definitely installed. In fact, when I use HttpClient as a static object (not injected into the page), it works fine--so I know for sure System.Net.Http is installed as a reference and working fine.

Problem is, when I run the page, I get the following error:

The type or namespace name 'HttpClient' does not exist in the namespace 'System.Net.Http' (are you missing an assembly reference?) [System.Diagnostics.DebuggerNonUserCodeAttribute()] public shared_page_aspx(System.Net.Http.HttpClient client) : base(client) { this.@__Init();

Why? 😭 Where is this weird code coming from?


Solution

  • Changed to singleton:

    container.RegisterSingleton<HttpClient>(new InjectionFactory(x => new HttpClient()));
    

    And also added this to web.config:

    <system.web>
        <compilation debug="true" targetFramework="4.8">
            <assemblies>
                <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"/>
            </assemblies>
        </compilation>
    </system.web>