示例#1
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create <SampleDbMigratorModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());
            }))
            {
                application.Initialize();

                await application
                .ServiceProvider
                .GetRequiredService <SampleDbMigrationService>()
                .MigrateAsync();

                application.Shutdown();

                _hostApplicationLifetime.StopApplication();
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create <AdminIdentityServerDbMigratorModule>(options =>
            {
                options.UseAutofac();
                // options
            }))
            {
                application.Initialize();

                AsyncHelper.RunSync(
                    () => application
                    .ServiceProvider
                    .GetRequiredService <AdminDbMigrationService>()
                    .MigrateAsync()
                    );

                application.Shutdown();
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            var application = AbpApplicationFactory.Create <MainModule>(options =>
            {
            });

            application.Initialize();

            var hello_interface = application.ServiceProvider.GetRequiredService <IHelloService>();

            hello_interface.Greeting();

            var hello_class = application.ServiceProvider.GetRequiredService <HelloService>();

            hello_class.Greeting();

            var hello_nihao = application.ServiceProvider.GetRequiredService <INiHao>();

            hello_nihao.SayHi();
        }
示例#4
0
        static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);       //注册实例?
            Console.OutputEncoding = System.Text.Encoding.GetEncoding("GB2312"); //修改输出的编码
            Console.WriteLine("欢迎来到学习(shangzhai)轮子的工具条。");
            //Console.WriteLine("English support?");
            //配置日志组件Serilog
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)                  //把微软的日志提升到告警才输出
                         .MinimumLevel.Override("Volo.Abp", Serilog.Events.LogEventLevel.Warning)                   //把abp框架的日志提升到告警才输出
                         .MinimumLevel.Override("System.Net.Http.HttpClient", Serilog.Events.LogEventLevel.Warning) //对类库System.Net.Http.HttpClient的日志提升
#if DEBUG
                         .MinimumLevel.Override("Cn.Abp.Cli", Serilog.Events.LogEventLevel.Debug)                   //调试模式下输出调试的信息
#else
                         .MinimumLevel.Override("Cn.Abp.Cli", Serilog.Events.LogEventLevel.Information)             //生产模式下输出信息
#endif
                         .Enrich.FromLogContext()                                                                   //这里是干嘛?
                         .WriteTo.File(Path.Combine(CliPaths.Log, "cn-abp-cli-logs"))                               //写日志文件
                         .WriteTo.Console()                                                                         //打印到控制台
                         .CreateLogger();                                                                           //创建日志

            //然后通过abp框架,加载模块,引用volo.abp.autofac
            //args = new string[] { "package-async", "-p", "E:\\GDProjects\\GD.Portal.PC.GzMes\\gd.portal.pc.gzmes\\src", "-o", "y", "-d", "C:\\Users\\user\\.nuget\\packages" };
            args = new string[] { "package-async", "-p", "E:\\GDProjects\\GD.Portal.PC.GzMes\\gd.portal.pc.gzmes\\src" };
            using (var application = AbpApplicationFactory.Create <CnAbpCliModule>(
                       options =>
            {
                options.UseAutofac();                             //依赖注入
                options.Services.AddLogging(c => c.AddSerilog()); //微软对serilog的拓展,添加服务的方式添加
            }))
            {
                application.Initialize();//初始化
                AsyncHelper.RunSync(
                    () => application.ServiceProvider
                    .GetRequiredService <CliService>()
                    .RunAsync(args)
                    );                  //但是这里没有注入日志组件啊?
                application.Shutdown(); //执行完命令后关闭所有依赖的模块
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            {
                // 根据启动模块创建 abp 应用
                var application = AbpApplicationFactory.Create <HelloAbpModule>(options =>
                {
                    // 集成 Autofac
                    options.UseAutofac();
                });
                // 初始化 abp 应用
                application.Initialize();
                // 获取应用中注册的服务
                var service = application.ServiceProvider.GetService <HelloWorldService>();
                // 调用应用中的服务方法
                service.Run();
            }


            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
示例#6
0
        static void Main(string[] args)
        {
            ConfigureLogging();

            using (var application = AbpApplicationFactory.Create <MaterialSystemDbMigratorModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());
            }))
            {
                application.Initialize();

                AsyncHelper.RunSync(
                    () => application
                    .ServiceProvider
                    .GetRequiredService <MaterialSystemDbMigrationService>()
                    .MigrateAsync());

                application.Shutdown();
            }
        }
示例#7
0
        static void Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create <AppModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(o => { o.AddConsole(); });

                options.Configuration.CommandLineArgs = args;
            }))
            {
                application.Initialize();

                var helloWorldService =
                    application.ServiceProvider.GetService <GeneratingService>();

                helloWorldService.Generate();

                //Console.WriteLine("Press ENTER to stop application...");
                //Console.ReadLine();
            }
        }
    public void CachedServiceProvider_Should_Cache_Services()
    {
        void TestResolvingServices(IServiceScope scope)
        {
            var cachedServiceProvider1 = scope.ServiceProvider.GetRequiredService <ICachedServiceProvider>();
            var cachedServiceProvider2 = scope.ServiceProvider.GetRequiredService <ICachedServiceProvider>();

            cachedServiceProvider1.ShouldBeSameAs(cachedServiceProvider2);

            var transientTestService1 = cachedServiceProvider1.GetRequiredService <TransientTestService>();
            var transientTestService2 = cachedServiceProvider2.GetRequiredService <TransientTestService>();

            transientTestService1.ShouldBeSameAs(transientTestService2);

            var cachedServiceProvider3 = cachedServiceProvider1.GetRequiredService <IServiceProvider>().GetRequiredService <ICachedServiceProvider>();

            cachedServiceProvider3.ShouldBeSameAs(cachedServiceProvider1);
        }

        using (var application = AbpApplicationFactory.Create <TestModule>())
        {
            application.Initialize();

            using (var scope1 = application.ServiceProvider.CreateScope())
            {
                TestResolvingServices(scope1);
                var testCounter = scope1.ServiceProvider.GetRequiredService <ITestCounter>();
                testCounter.GetValue(nameof(TransientTestService)).ShouldBe(1);
            }

            using (var scope2 = application.ServiceProvider.CreateScope())
            {
                TestResolvingServices(scope2);
                var testCounter = scope2.ServiceProvider.GetRequiredService <ITestCounter>();

                //Resolved in a different scope, so should not cache the service!
                testCounter.GetValue(nameof(TransientTestService)).ShouldBe(2);
            }
        }
    }
示例#9
0
        static void Main(string[] args)
        {
            var application = AbpApplicationFactory.Create <MainModule>(options =>
            {
            });

            application.Initialize();

            var fileProvider = application.ServiceProvider.GetRequiredService <IVirtualFileProvider>();

            /* load resource file in this assembly */
            Console.WriteLine("loading from this assembly");
            var thisManifestFile = fileProvider.GetFileInfo("/settings/manifest_setting.json");

            Console.WriteLine(thisManifestFile.ReadAsString());
            var thisPhysicalFile = fileProvider.GetFileInfo("physical_setting.json");

            Console.WriteLine(thisPhysicalFile.ReadAsString());
            Console.WriteLine("-----------------------------------------------------------------------------");

            /* load resource file from dependent assembly*/
            Console.WriteLine("loading from dependent assembly");
            var baseManifestFile = fileProvider.GetFileInfo("/settings/base_manifest_setting.json");

            Console.WriteLine(baseManifestFile.ReadAsString());
            var basePhysicalFile = fileProvider.GetFileInfo("base_physical_setting.json");

            Console.WriteLine(basePhysicalFile.ReadAsString());
            Console.WriteLine("-----------------------------------------------------------------------------");

            /* get resource file conflict */
            Console.WriteLine("loading conflict");
            var conflictManifestFile = fileProvider.GetFileInfo("/settings/conflict_manifest_setting.json");

            Console.WriteLine(conflictManifestFile.ReadAsString());
            var conflictPhysiclaFile = fileProvider.GetFileInfo("conflict_physical_setting.json");

            Console.WriteLine(conflictPhysiclaFile.ReadAsString());
            Console.WriteLine("-----------------------------------------------------------------------------");
        }
示例#10
0
        /// <summary>
        /// Use default chain id.
        /// </summary>
        /// <param name="keyPair"></param>
        public ContractTester(ECKeyPair keyPair)
        {
            Application =
                AbpApplicationFactory.Create <TContractTestAElfModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddTransient(o =>
                {
                    var mockService = new Mock <IAccountService>();
                    mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                              Task.FromResult(CryptoHelper.SignWithPrivateKey(keyPair.PrivateKey, data)));

                    mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(keyPair.PublicKey);

                    return(mockService.Object);
                });
            });

            Application.Initialize();

            KeyPair = keyPair;
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            using (var application = AbpApplicationFactory.Create <GrpcDemoConsoleApiClientModule>())
            {
                application.Initialize();


                /* Disabled regular REST request demo since it is not working when
                 * the server runs with HTTP/2.
                 */

                //var demo = application.ServiceProvider.GetRequiredService<ClientDemoService>();
                //await demo.RunAsync();

                var grpcDemo = application.ServiceProvider.GetRequiredService <GrpcClientDemoService>();
                await grpcDemo.RunAsync();

                application.Shutdown();
            }
        }
        private IAbpApplication CreateApplication <T>(ChainInitializationDto dto) where T : AbpModule
        {
            var application =
                AbpApplicationFactory.Create <T>(options =>
            {
                options.UseAutofac();
                options.Services.Configure <ChainOptions>(o => { o.ChainId = dto.ChainId; });

                options.Services.Configure <ChainInitializationOptions>(o =>
                {
                    o.Symbol        = dto.Symbol;
                    o.ChainId       = dto.ChainId;
                    o.ParentChainId = dto.ParentChainId;
                    o.CreationHeightOnParentChain             = dto.CreationHeightOnParentChain;
                    o.ParentChainTokenContractAddress         = dto.ParentChainTokenContractAddress;
                    o.RegisterParentChainTokenContractAddress = dto.RegisterParentChainTokenContractAddress;
                });
            });

            application.Initialize();
            return(application);
        }
示例#13
0
文件: Program.cs 项目: zredb/abp
        static async Task Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create <MyConsoleModule>(options =>
            {
                options.Configuration.CommandLineArgs = args;
                options.UseAutofac();
            }))
            {
                Console.WriteLine("Initializing the application...");
                application.Initialize();
                Console.WriteLine("Initializing the application... OK");

                Console.WriteLine("Checking configuration...");

                var configuration = application.ServiceProvider.GetRequiredService <IConfiguration>();
                if (configuration["AppSettingKey1"] != "AppSettingValue1")
                {
                    Console.WriteLine("ERROR: Could not read the configuration!");
                    Console.WriteLine("Press ENTER to exit!");
                    Console.ReadLine();
                    return;
                }

                Console.WriteLine();
                Console.WriteLine("Checking configuration... OK");

                var writers = application.ServiceProvider.GetServices <IMessageWriter>();
                foreach (var writer in writers)
                {
                    writer.Write();
                }


                Console.WriteLine();
                Console.WriteLine("Press ENTER to exit!");
                Console.ReadLine();
            }
        }
示例#14
0
文件: Program.cs 项目: younes21/abp
    private static async Task Main(string[] args)
    {
        Console.OutputEncoding = System.Text.Encoding.UTF8;

        Log.Logger = new LoggerConfiguration()
                     .MinimumLevel.Information()
                     .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                     .MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning)
                     .MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
                     .MinimumLevel.Override("Volo.Abp.IdentityModel", LogEventLevel.Information)
#if DEBUG
                     .MinimumLevel.Override("Volo.Abp.Cli", LogEventLevel.Debug)
#else
                     .MinimumLevel.Override("Volo.Abp.Cli", LogEventLevel.Information)
#endif
                     .Enrich.FromLogContext()
                     .WriteTo.File(Path.Combine(CliPaths.Log, "abp-cli-logs.txt"))
                     .WriteTo.Console()
                     .CreateLogger();

        using (var application = AbpApplicationFactory.Create <AbpCliModule>(
                   options =>
        {
            options.UseAutofac();
            options.Services.AddLogging(c => c.AddSerilog());
        }))
        {
            application.Initialize();

            await application.ServiceProvider
            .GetRequiredService <CliService>()
            .RunAsync(args);

            application.Shutdown();

            Log.CloseAndFlush();
        }
    }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create <AbpToAzureDbMigratorModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());

                // Add this line of code to make it possible read from appsettings.Staging.json
                options.Services.ReplaceConfiguration(BuildConfiguration());
            }))
            {
                application.Initialize();

                await application
                .ServiceProvider
                .GetRequiredService <AbpToAzureDbMigrationService>()
                .MigrateAsync();

                application.Shutdown();

                _hostApplicationLifetime.StopApplication();
            }
        }
示例#16
0
        //static void Main(string[] args)
        //{
        //    using (var application = AbpApplicationFactory.Create<AppModule>())
        //    {
        //        application.Initialize();

        //        #region 1
        //        //Console.WriteLine("Press ENTER to stop application...");
        //        //Console.ReadLine();
        //        #endregion

        //        //Resolve a service and use it
        //        var helloWorldService =
        //            application.ServiceProvider.GetService<HelloWorldService>();
        //        helloWorldService.SayHello();

        //        Console.WriteLine("Press ENTER to stop application...");
        //        Console.ReadLine();

        //    }
        //   //Console.WriteLine("Hello World!");
        //}


        static void Main(string[] args)
        {
            using
            (var application = AbpApplicationFactory.Create <AppModule>
                               (
                 options =>
            {
                options.UseAutofac();         //Autofac integration
            }
                               )
            )
            {
                application.Initialize();

                //Resolve a service and use it
                var helloWorldService =
                    application.ServiceProvider.GetService <HelloWorldService>();
                helloWorldService.SayHello();

                Console.WriteLine("Press ENTER to stop application...");
                Console.ReadLine();
            }
        }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (IAbpApplicationWithInternalServiceProvider application = AbpApplicationFactory.Create <SnookerDbMigratorModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());

                // Not added by ABP.io framework
                options.Services.ReplaceConfiguration(BuildConfiguration());
            }))
            {
                application.Initialize();

                await application
                .ServiceProvider
                .GetRequiredService <SnookerDbMigrationService>()
                .MigrateAsync();

                application.Shutdown();

                _hostApplicationLifetime.StopApplication();
            }
        }
示例#18
0
        static void Main(string[] args)
        {
            //AbpApplicationFactory.Create 加载 Abp_Module 启动模块.块. Initialize()方法初始化.
            var application = AbpApplicationFactory.Create <Abp_Module>();

            application.Initialize();

            // ServiceProvider 引用应用程序使用的根服务提供者。在初始化应用程序之前不能使用它。
            // GetService/GetRequiredService  必须using Microsoft.Extensions.DependencyInjection;
            // 注入依赖 这里感觉更像是 通过反射获取服务
            // 这个服务是通过继承依赖接口来实现将服务放到容器中  当前服务是继承了 ITransientDependency
            // 获取服务时,会进行依赖注入
            // 最好使用GetRequiredService  因为如果出错 报错更快 https://www.cnblogs.com/yilezhu/p/11107648.html
            var helloWoldService = application.ServiceProvider.GetRequiredService <HelloWorldService>();

            helloWoldService.DoIt();
            HelloWorldService.TFWrite();

            var helloService1 = application.ServiceProvider.GetRequiredService <HelloService>();

            helloService1.Writer();
            HelloService.TFWrite();
            var helloService2 = application.ServiceProvider.GetRequiredService <Hello2Service>();

            helloService2.Writer();
            //使用Fac
            var Afcapplication = AbpApplicationFactory.Create <Afc_Module>(options =>
            {
                options.UseAutofac();
            });

            Afcapplication.Initialize();

            var AfcService = Afcapplication.ServiceProvider.GetRequiredService <AfcService>();

            AfcService.DoIt();
        }
示例#19
0
        private static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                         .MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning)
#if DEBUG
                         .MinimumLevel.Override("Volo.Abp.Cli", LogEventLevel.Debug)
#else
                         .MinimumLevel.Override("Volo.Abp.Cli", LogEventLevel.Information)
#endif
                         .Enrich.FromLogContext()
                         .WriteTo.File(Path.Combine(CliPaths.Log, "abp-cli-logs.txt"))
                         .WriteTo.Console()
                         .CreateLogger();

            using (var application = AbpApplicationFactory.Create <AbpCliModule>(
                       options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());
            }))
            {
                application.Initialize();

                AsyncHelper.RunSync(
                    async() => {
                    await application.ServiceProvider.GetRequiredService <CliService>().RunAsync(args);
                    System.Console.Read();
                    return(Task.CompletedTask);
                }
                    );

                application.Shutdown();
            }
        }
示例#20
0
        static async Task Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create <TextTemplateDemoModule>(options =>
            {
                options.UseAutofac();
            }))
            {
                application.Initialize();

                var helloDemo           = application.ServiceProvider.GetRequiredService <HelloDemo>();
                var passwordResetDemo   = application.ServiceProvider.GetRequiredService <PasswordResetDemo>();
                var welcomeEmailDemo    = application.ServiceProvider.GetRequiredService <WelcomeEmailDemo>();
                var globalContextDemo   = application.ServiceProvider.GetRequiredService <GlobalContextUsageDemo>();
                var templateContentDemo = application.ServiceProvider.GetRequiredService <TemplateContentDemo>();

                await helloDemo.RunAsync();

                await helloDemo.RunWithAnonymousModelAsync();

                await passwordResetDemo.RunAsync();

                await welcomeEmailDemo.RunAsync("en");

                await welcomeEmailDemo.RunAsync("tr");

                await globalContextDemo.RunAsync();

                await templateContentDemo.RunAsync();

                Console.WriteLine();
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();

                application.Shutdown();
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            using (var application = AbpApplicationFactory.Create <AppModule>(options =>
            {
                options.UseAutofac(); //Autofac integration
            }))
            {
                application.Initialize();

                //Resolve a service and use it
                var _clienteAppService = application.ServiceProvider.GetService <IClienteAppService>();

                CreateUpdateClienteDto clienteDto = new CreateUpdateClienteDto();
                clienteDto.Nome       = "teste";
                clienteDto.Observacao = "teste";
                _clienteAppService.CreateAsync(clienteDto);


                var result = _clienteAppService.GetListAsync(new GetClienteInput());

                Console.WriteLine("Press ENTER to stop application...");
                Console.ReadLine();
            }
        }
示例#22
0
    public void Should_Initialize_Single_Module()
    {
        using (var application = AbpApplicationFactory.Create <IndependentEmptyModule>())
        {
            //Assert
            var module = application.Services.GetSingletonInstance <IndependentEmptyModule>();
            module.PreConfigureServicesIsCalled.ShouldBeTrue();
            module.ConfigureServicesIsCalled.ShouldBeTrue();
            module.PostConfigureServicesIsCalled.ShouldBeTrue();

            //Act
            application.Initialize();

            //Assert
            application.ServiceProvider.GetRequiredService <IndependentEmptyModule>().ShouldBeSameAs(module);
            module.OnApplicationInitializeIsCalled.ShouldBeTrue();

            //Act
            application.Shutdown();

            //Assert
            module.OnApplicationShutdownIsCalled.ShouldBeTrue();
        }
    }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create <AppModule>(options =>
            {
                options.UseAutofac(); //Autofac integration
            }))
            {
                application.Initialize();

                //Resolve a service and use it

                Console.WriteLine(application.ServiceProvider.GetRequiredService <ICurrentActive>().Active);
                var orderSyncJob = application.ServiceProvider.GetService <OrderSyncJob>();
                await orderSyncJob.ExecuteAsync(new OrderSyncJobArgs()
                {
                    Active = false
                });

                Console.WriteLine(application.ServiceProvider.GetRequiredService <ICurrentActive>().Active);
                application.Shutdown();
            }

            //return Task.CompletedTask;
        }
示例#24
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create <ScoringDbMigratorModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());
#if DEBUG
                options.Configuration.EnvironmentName = "Development";
                options.Configuration.UserSecretsAssembly = typeof(DbMigratorHostedService).Assembly;
#endif
            }))
            {
                application.Initialize();

                await application
                .ServiceProvider
                .GetRequiredService <ScoringDbMigrationService>()
                .MigrateAsync();

                application.Shutdown();

                _hostApplicationLifetime.StopApplication();
            }
        }
示例#25
0
        static async Task Main(string[] args)
        {
            string inputPath  = args[0];
            string outputPath = args[1];

            using (var application = AbpApplicationFactory.Create <BugdiggerConsoleHostModule>(option => {
                option.UseAutofac();
            }))
            {
                application.Initialize();
                var xmlService         = application.ServiceProvider.GetService <XmlService>();
                var testExecAppService = application.ServiceProvider.GetService <ITestExecAppService>();

                var project     = xmlService.ReadStr <Project>(File.ReadAllText(inputPath));
                var testResults = new List <TestResultDto>();
                foreach (var testflow in project.Testflow)
                {
                    foreach (var step in testflow.step)
                    {
                        for (int i = 0; i < step.exectimes; i++)
                        {
                            if (step.delaytime > 0)
                            {
                                await Task.Delay(step.delaytime);
                            }
                            string configpath = "";
                            if (step.xmlPath != "")
                            {
                                configpath = step.xmlPath + "/" + step.xmlname;
                                Console.WriteLine(configpath);
                            }
                            else
                            {
                                int index = inputPath.LastIndexOf("/");
                                configpath = inputPath.Substring(0, index + 1) + "/" + step.xmlname;
                                Console.WriteLine(configpath);
                            }
                            string text        = File.ReadAllText(configpath);
                            var    testCaseDto = new TestCaseDto()
                            {
                                Name   = step.xmlname,
                                Script = text
                            };
                            var testResult = await testExecAppService.CreateAsync(testCaseDto);

                            if (testResult != null)
                            {
                                testResults.AddRange(testResult);
                            }
                        }
                    }
                }
                if (testResults.Count == 0)
                {
                    Console.WriteLine("No result!");
                    return;
                }

                File.WriteAllText(outputPath, JsonConvert.SerializeObject(testResults));

                Console.WriteLine("Auto Test Finish!");
            }
        }
示例#26
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create <WechatyConsoleModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(loggingBuilder =>
                {
                    loggingBuilder.AddSerilog(dispose: true);
                });

                // 绑定插件,方式一:加载模块 方式二:加载 dll
                // TODO 这里可以读取所有继承 WechatyPluginBaseModule的模块,动态读取
                options.PlugInSources.AddTypes(
                    typeof(WechatyDingDongModule),
                    typeof(WechatyQRCodeTerminalModule),
                    typeof(WechatyPlugInWeatherModule));
            }))
            {
                application.Initialize();

                configuration = application.ServiceProvider.GetRequiredService <IConfiguration>();


                WechatyOptions wechatyOptions = new WechatyOptions()
                {
                    Token    = configuration["Wechaty_Token"],
                    Name     = configuration["Wechaty_Name"],
                    EndPoint = configuration["Wechaty_EndPoint"]
                };

                // Bo
                bot = application.ServiceProvider.GetRequiredService <IWechatyBotService>();

                // 插件服务注册
                //var plugin = application.ServiceProvider.GetRequiredService<WechatyPluginBaseModule>();
                var qrCodePlugin   = application.ServiceProvider.GetRequiredService <QRCodeTerminalAppService>();
                var dingdongPlugin = application.ServiceProvider.GetRequiredService <DingDongAppService>();
                var weatherPlugin  = application.ServiceProvider.GetRequiredService <WeatherPlugInService>();

                bot.Instance(wechatyOptions);

                // Scan Event Plugin
                qrCodePlugin.QRCodeTerminalAsAscii();

                // Message Event Plugin
                dingdongPlugin.DingDong();

                // 直接监听
                bot.On <EventMessagePayload>(EventEnum.Message, async(eventData) =>
                {
                    var Message = bot.Message();
                    var payload = await Message.Ready(eventData.MessageId);

                    if (payload.Text == "天王盖地虎")
                    {
                        await Message.Say("宝塔镇河妖", payload);
                    }
                    if (payload.Text.Contains("天气"))
                    {
                        var city        = payload.Text.Split("天气").Where(x => x != "天气").FirstOrDefault();
                        var weatherInfo = await weatherPlugin.GetWeatherAsync(new PlugIn.Weather.InputDto()
                        {
                            Token = "c7601763d0a241568f75213509012c48",
                            City  = city
                        });
                    }
                });

                await bot.Start();
            }
        }