I have a project .Net Core in React and, to save time, I would like to test a method to export files by a Console Application. But I can't to implement the DI in my console, here's the error:
Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[MyPrj.Managers.Managers.Implementations.MyLogManager]' while attempting to activate 'MyPrj.Managers.Managers.Implementations.MyLogManager'.
This is a simplified version of my Program.cs:
class Program
{
public static IConfigurationRoot Configuration;
public static ServiceProvider serviceProvider;
public static void Main(string[] args)
{
var services = new ServiceCollection();
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json", optional: true);
Configuration = builder.Build();
services.AddDbContext<MyDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.Configure<MailOptions>(Configuration.GetSection("EmailSettings"));
[... other options...]
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<ILogManager, MyLogManager>();
services.AddScoped<IMailManager, MailManager>();
[... other services ...]
services.AddScoped<IDocumentationManager, DocumentationManager>();
serviceProvider = services.BuildServiceProvider();
MainAsync().GetAwaiter().GetResult();
Console.WriteLine("END");
Console.ReadKey();
}
private static async Task MainAsync()
{
await ExportAsync();
}
public static async Task ExportAsync()
{
using (MyDBContext dbContext = serviceProvider.GetService<MyDBContext>())
{
List<User> user = dbContext.Users.ToList();
var logger = serviceProvider.GetService<ILogManager>();
var docManager = serviceProvider.GetService<IDocumentationManager>();
string userAnswer = Console.ReadLine();
var file = await docManager.GetUser(userAnswer);
File.WriteAllBytes("C:\tmp\user.txt", file.File);
}
}
}
Thanks to all,
it has been enough adding services.AddLogging()
, following @Steven 's advice, to solve my problem.