4

How can I add more servicies to DI? as for now only ConvertService is DI when i was trying to add another one for example

services.AddTransient<Authorization>();

it has not effect and i cannot DI Authorization service to other classes. How to handle if i want to add more servicies to be added to DI. Also i can only inject IHttpCLient to ConvertService

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading.Tasks;

namespace ProtocolConvert
{
    class Program
    {
       private static IConfigurationRoot Configuration { get; set; }
        static async Task Main(string[] args)
        {

            IConfigurationBuilder builder = new ConfigurationBuilder()

            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
            Configuration = builder.Build();

            var host = Host.CreateDefaultBuilder()
                .ConfigureServices((context, services) =>
                {
                    services.AddHttpClient("GitHub", httpClient =>
                     {
                         httpClient.BaseAddress = new Uri(Configuration.GetSection("tokenUrl").Value);
                         httpClient.DefaultRequestHeaders.Add(
                              "X-API-ID", Configuration.GetSection("X-API-ID").Value);
                         httpClient.DefaultRequestHeaders.Add(
                             "X-API-SECRET", Configuration.GetSection("X-API-SECRET").Value);
                     });
                   
                    services.AddTransient<ConvertService>();
                 
                }).Build();

            var svc = ActivatorUtilities.CreateInstance<ConvertService>(host.Services);
          
            await svc.ConvertToCsv();
        }
       


    }
}

1 Answer 1

3

I'm not pretty sure of the purpose of your implementation. But I think you should use GetService<ConvertService>() instead of create a new instance of your service class.

You can see an example here https://siderite.dev/blog/creating-console-app-with-dependency-injection-in-/

I hope this helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.