受欢迎的博客标签

In this article, I will discuss as follow:

.Net core 3.x

How to Use dependency injection in a .Net Core console application.

How to Use Logging in Console App Program.

 

step 1:Use dependency injection in a .Net Core console application

  var serviceCollection = new ServiceCollection();
            serviceCollection.AddHttpClient();
            serviceCollection.AddLogging();
            serviceCollection.AddSingleton<TimerTasks.TaskList>();

            var serviceProvider = serviceCollection.BuildServiceProvider();

step 2:configure console logging  in a .Net Core console application

 class Program
    {
        static void Main(string[] args)
        {
            // Use dependency injection in a .Net Core console application
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddHttpClient();
            serviceCollection.AddLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                loggingBuilder.AddConsole();
            });
            serviceCollection.AddSingleton<TimerTasks.TaskList>();

            var serviceProvider = serviceCollection.BuildServiceProvider();
         }  
     }

 

using System;

using System.Threading;
using System.Net.Http;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace TimerTask
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use dependency injection in a .Net Core console application
            var serviceCollection = new ServiceCollection();//  prepare dependency injection 
            serviceCollection.AddHttpClient();

            //configure console logging
            serviceCollection.AddLogging(loggingBuilder =>
            {
                loggingBuilder.SetMinimumLevel(LogLevel.Debug);
                loggingBuilder.AddConsole();
            });
            serviceCollection.AddSingleton<TimerTasks.TaskList>();

            var serviceProvider = serviceCollection.BuildServiceProvider(); /* create types */




            ;
            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            var logger = loggerFactory.CreateLogger("Program");


           
            logger.LogInformation(DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString() + " www.iaspnetcore.com TimerTask Starting ...");