Reputation: 246
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();
}
}
}
Upvotes: 4
Views: 4438
Reputation: 51
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.
Upvotes: 3