ABP-Console


1.Module模块

 

1.Console项目:

1.1 基础:Net5.0 VS2019

1.2 目标:实现abp的module

1.3 实现步骤:

  1. 引入Volo.abp.core,Volo.Abp.Autofac

  2. 自定义abpmodule类

      
     /// 
        /// 使用ABP Module
        /// 
        [DependsOn(
         typeof(AbpAutofacModule)
        )]
        class ConsoleModule : AbpModule
        {
            public override void ConfigureServices(ServiceConfigurationContext context)
            {
                // 1、IOC注册自定义类
                System.Console.WriteLine("加载AbpModuleModule模块");
                // context.Services.AddSingleton();
                context.Services.AddHostedService();
            }
        }

     

  3. 实现IHostedService类

    public class ConsoleHostedService : IHostedService
        {
            private readonly HelloWorldService _helloWorldService;
    ?
            public ConsoleHostedService(HelloWorldService helloWorldService)
            {
                _helloWorldService = helloWorldService;
            }
            public Task StartAsync(CancellationToken cancellationToken)
            {
                _helloWorldService.SayHello();
                return Task.CompletedTask;
            }
    ?
            public Task StopAsync(CancellationToken cancellationToken)
            {
                return Task.CompletedTask;
            }
        }

     

  4. 添加service类

      
      /// 
        /// 服务类
        /// 
        [Dependency(ServiceLifetime.Transient)] //这里推荐使用特性注册,abp推荐的做法
        public class HelloWorldService/* : ITransientDependency*/
        {
            public void SayHello()
            {
                System.Console.WriteLine("hello world");
            }
        }

     

  5. 在startup.cs添加启动类

    public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                //添加所有服务到IOC容器
                services.AddApplication();
                    
                //    options =>
                //{
                //    // 1.加载插件
                //    options.PlugInSources.AddFolder("");
                //});
            }
    }

     

  6. 运行结果如下:

    console......
    加载AbpModuleModule模块
    hello world
    info: Microsoft.Hosting.Lifetime[0]
         Now listening on: http://localhost:5000
    info: Microsoft.Hosting.Lifetime[0]
         Application started. Press Ctrl+C to shut down.
    info: Microsoft.Hosting.Lifetime[0]
         Hosting environment: Development
    info: Microsoft.Hosting.Lifetime[0]
         Content root path: C:\Users\MaiBenBen\Desktop\报班学习\abp\AbpConsole\AbpConsole

     将原来的东西放到ConsoleModule中。 

ABP