Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. .NET (Core and Framework)
  4. Question about Dependency Injection

Question about Dependency Injection

Scheduled Pinned Locked Moved .NET (Core and Framework)
jsonhelpquestioncsharpdotnet
6 Posts 6 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Offline
    F Offline
    Fred2834
    wrote on last edited by
    #1

    Hello guys, I have an issue related to dependency injection in the Program.cs of a .Net 7 application. In this case it's an API, but that does not really matter. Before calling the line: var app = builder.Build(); I am adding a few singletons normally with :

    builder.Services.AddSingleton();
    builder.Services.AddSingleton();

    My issue is that the HTTP client singleton requires info from the config singleton, and it's not a simple case of injecting the former into the latter. We can't use appsettings.json to manage our configuration, that would be too easy, and because the second one is an HTTP client, I have this code :

    builder.Services.AddSingleton();
    builder.Services.AddHttpClient(client =>
    {
    client.BaseAddress = new Uri(myConfig.myURI);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    }).ConfigurePrimaryHttpMessageHandler(() =>
    {
    return new HttpClientHandler()
    {
    UseDefaultCredentials = true
    };
    });

    .. all this still before I call builder.Build(); I have already googled and chatGPT'd the problem, but the solutions I get are for .Net 6 at best, and do not apply. My current solution is to use builder.Services.BuildServiceProvider().GetService() to get an instance of myConfig, but then the builder is called twice, so this instance is lost, and after the builder.Build(), I have to read my config again. Technically, this works, but it's ugly and triggers my OCD. If there's any DI god out there, what am I missing ? :) Thanks in advance Fred

    L J B R 4 Replies Last reply
    0
    • F Fred2834

      Hello guys, I have an issue related to dependency injection in the Program.cs of a .Net 7 application. In this case it's an API, but that does not really matter. Before calling the line: var app = builder.Build(); I am adding a few singletons normally with :

      builder.Services.AddSingleton();
      builder.Services.AddSingleton();

      My issue is that the HTTP client singleton requires info from the config singleton, and it's not a simple case of injecting the former into the latter. We can't use appsettings.json to manage our configuration, that would be too easy, and because the second one is an HTTP client, I have this code :

      builder.Services.AddSingleton();
      builder.Services.AddHttpClient(client =>
      {
      client.BaseAddress = new Uri(myConfig.myURI);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

      }).ConfigurePrimaryHttpMessageHandler(() =>
      {
      return new HttpClientHandler()
      {
      UseDefaultCredentials = true
      };
      });

      .. all this still before I call builder.Build(); I have already googled and chatGPT'd the problem, but the solutions I get are for .Net 6 at best, and do not apply. My current solution is to use builder.Services.BuildServiceProvider().GetService() to get an instance of myConfig, but then the builder is called twice, so this instance is lost, and after the builder.Build(), I have to read my config again. Technically, this works, but it's ugly and triggers my OCD. If there's any DI god out there, what am I missing ? :) Thanks in advance Fred

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      If you're "stuck" with a given framework, count yourself lucky if you get something to work. When it does, move on instead of thinking about "ugly"; it's a waste of time.

      "Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I

      H 1 Reply Last reply
      0
      • F Fred2834

        Hello guys, I have an issue related to dependency injection in the Program.cs of a .Net 7 application. In this case it's an API, but that does not really matter. Before calling the line: var app = builder.Build(); I am adding a few singletons normally with :

        builder.Services.AddSingleton();
        builder.Services.AddSingleton();

        My issue is that the HTTP client singleton requires info from the config singleton, and it's not a simple case of injecting the former into the latter. We can't use appsettings.json to manage our configuration, that would be too easy, and because the second one is an HTTP client, I have this code :

        builder.Services.AddSingleton();
        builder.Services.AddHttpClient(client =>
        {
        client.BaseAddress = new Uri(myConfig.myURI);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        }).ConfigurePrimaryHttpMessageHandler(() =>
        {
        return new HttpClientHandler()
        {
        UseDefaultCredentials = true
        };
        });

        .. all this still before I call builder.Build(); I have already googled and chatGPT'd the problem, but the solutions I get are for .Net 6 at best, and do not apply. My current solution is to use builder.Services.BuildServiceProvider().GetService() to get an instance of myConfig, but then the builder is called twice, so this instance is lost, and after the builder.Build(), I have to read my config again. Technically, this works, but it's ugly and triggers my OCD. If there's any DI god out there, what am I missing ? :) Thanks in advance Fred

        J Offline
        J Offline
        jschell
        wrote on last edited by
        #3

        If you want a singleton then you have to inject it into a thread flow that does not depend on requests but rather something like the start up method. But as with the other reply, the point it to deliver something. And you need to have a realistic view about what might actually need to be easily replaced in the future. So does it actually need to be injected. Configuration might be it but you can do that with a standard factory idiom also.

        1 Reply Last reply
        0
        • F Fred2834

          Hello guys, I have an issue related to dependency injection in the Program.cs of a .Net 7 application. In this case it's an API, but that does not really matter. Before calling the line: var app = builder.Build(); I am adding a few singletons normally with :

          builder.Services.AddSingleton();
          builder.Services.AddSingleton();

          My issue is that the HTTP client singleton requires info from the config singleton, and it's not a simple case of injecting the former into the latter. We can't use appsettings.json to manage our configuration, that would be too easy, and because the second one is an HTTP client, I have this code :

          builder.Services.AddSingleton();
          builder.Services.AddHttpClient(client =>
          {
          client.BaseAddress = new Uri(myConfig.myURI);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

          }).ConfigurePrimaryHttpMessageHandler(() =>
          {
          return new HttpClientHandler()
          {
          UseDefaultCredentials = true
          };
          });

          .. all this still before I call builder.Build(); I have already googled and chatGPT'd the problem, but the solutions I get are for .Net 6 at best, and do not apply. My current solution is to use builder.Services.BuildServiceProvider().GetService() to get an instance of myConfig, but then the builder is called twice, so this instance is lost, and after the builder.Build(), I have to read my config again. Technically, this works, but it's ugly and triggers my OCD. If there's any DI god out there, what am I missing ? :) Thanks in advance Fred

          B Offline
          B Offline
          Bohdan Stupak
          wrote on last edited by
          #4

          I'm not sure why you do things exactly this way but it seems to me that you're struggling because you're doing something you're not supposed to do with HTTP clients. Here are some nice reads about IHttpClientFactory. I think they'll help you to instantiate your HttpClient in a more robust way. Use the IHttpClientFactory - .NET | Microsoft Learn[^] Use IHttpClientFactory to implement resilient HTTP requests | Microsoft Learn[^]

          1 Reply Last reply
          0
          • L Lost User

            If you're "stuck" with a given framework, count yourself lucky if you get something to work. When it does, move on instead of thinking about "ugly"; it's a waste of time.

            "Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I

            H Offline
            H Offline
            Hyper GoGo
            wrote on last edited by
            #5

            Our everyday lives depend heavily on personal mobility in today's fast-paced society. We are constantly searching for new and effective commuting methods, Hyper GoGo is leading the charge. The amazing universe of Hyper GoGo, its distinctive traits, and its effects on individual mobility are all explored in this essay.

            1 Reply Last reply
            0
            • F Fred2834

              Hello guys, I have an issue related to dependency injection in the Program.cs of a .Net 7 application. In this case it's an API, but that does not really matter. Before calling the line: var app = builder.Build(); I am adding a few singletons normally with :

              builder.Services.AddSingleton();
              builder.Services.AddSingleton();

              My issue is that the HTTP client singleton requires info from the config singleton, and it's not a simple case of injecting the former into the latter. We can't use appsettings.json to manage our configuration, that would be too easy, and because the second one is an HTTP client, I have this code :

              builder.Services.AddSingleton();
              builder.Services.AddHttpClient(client =>
              {
              client.BaseAddress = new Uri(myConfig.myURI);
              client.DefaultRequestHeaders.Accept.Clear();
              client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

              }).ConfigurePrimaryHttpMessageHandler(() =>
              {
              return new HttpClientHandler()
              {
              UseDefaultCredentials = true
              };
              });

              .. all this still before I call builder.Build(); I have already googled and chatGPT'd the problem, but the solutions I get are for .Net 6 at best, and do not apply. My current solution is to use builder.Services.BuildServiceProvider().GetService() to get an instance of myConfig, but then the builder is called twice, so this instance is lost, and after the builder.Build(), I have to read my config again. Technically, this works, but it's ugly and triggers my OCD. If there's any DI god out there, what am I missing ? :) Thanks in advance Fred

              R Offline
              R Offline
              Rob Philpott
              wrote on last edited by
              #6

              Ok, a few months late admittedly. I'm not a fan of all this functional style boostrapping in ASP.NET core. I find the whole thing obfuscated and difficult to work with and often grapple just to do something simple like config or logging. Anyway, I have this in my code:

              services.AddHttpClient((serviceProvider, httpClient) =>
              {
              var opts = serviceProvider.GetRequiredService>();
              httpClient.BaseAddress = opts.Value.BaseUrl;
              })

              So, if you just want to get access to config, I think you can just retrieve it from the service provider given as the second parameter to the lambda, no BuildServiceProvider() required.

              Regards, Rob Philpott.

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups