[.NET Core] 動態註冊IHostedService範例 - 使用Autofac

[.NET] 動態註冊IHostedService範例 - 使用Autofac

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host
                .CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacServiceProviderFactory())                
                .ConfigureContainer<Autofac.ContainerBuilder>((containerBuilder) =>
                {
                    containerBuilder
                        .RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                        .As<IHostedService>();
                })
            ;
        }
    }

    public class ClarkApp : IHostedService
    {
        // Fields
        private readonly ILogger<ClarkApp> _logger = null;

        private readonly IHostEnvironment _hostEnvironment = null;


        // Constructors
        public ClarkApp(ILogger<ClarkApp> logger, IHostEnvironment hostEnvironment)
        {
            #region Contracts

            if (logger == null) throw new ArgumentException();
            if (hostEnvironment == null) throw new ArgumentException();

            #endregion

            // Default
            _logger = logger;
            _hostEnvironment = hostEnvironment;
        }


        // Methods
        public Task StartAsync(CancellationToken cancellationToken)
        {
            // Notify
            Console.WriteLine("ClarkApp:StartAsync");

            // Return
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            // Notify
            Console.WriteLine("ClarkApp:StopAsync");

            // Return
            return Task.CompletedTask;
        }
    }
}

 

期許自己
能以更簡潔的文字與程式碼,傳達出程式設計背後的精神。
真正做到「以形寫神」的境界。