zoukankan      html  css  js  c++  java
  • Net Core的启动项Program

    在WebApi的项目中和在控制台中都是有Program启动项的身影

    API中基本就是下面的这样,基本是不动,而是把配置的信息,放在StartUp中
    namespace
    HubAPI { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>();//可以看到这里是去出发StartUp这个类了。 }); } }
    namespace HubAPI
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    IConfiguration 是用来加载配置值的,可以加载内存键值对、JSON或XML配置文件,我们通常用来加载缺省的appsettings.json .
    public IConfiguration Configuration { get; }

    下面这个参数Services :指定服务描述符集合的协定(就是说,你需要的服务就是要在这个里面进行Add,下面的每一个服务都是Add开头的)
    public void ConfigureServices(IServiceCollection services) { services.AddControllers();
    //这个是绑定GetSection--》AppSetting
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    /

    绑定数据库db,就这个Configuration就可以读取到Appsettings.Json的数据了 string conn = Configuration.GetConnectionString("db"); services.AddDbContext<HubData.ACC_MINIEHUBContext> ( p => p.UseSqlServer(conn).EnableSensitiveDataLogging() ); //service bus services.AddSingleton<ITopicClient>(x => { return new TopicClient(Configuration.GetConnectionString("azure"), "servicesbus2topic1"); }); services.AddApiVersioning(option => { option.ReportApiVersions = true; option.AssumeDefaultVersionWhenUnspecified = true; option.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); }); services.AddHttpClient(); services.AddTransient<HubService.SOService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
    {
      "ConnectionStrings": {
        "db": "锄禾日当午"    
      },
    
      "AppSettings": {   
        "静夜思": "李白",
        "悯农": "李绅"
      },
    
      "Logging": {
        "LogLevel": {
          "Default": "Trace",
          "Microsoft": "Information"
        }
      },
      "AllowedHosts": "*"
    }

    下面说下控制台应用程序的配置怎么搞

    using HubDatetime;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    using System;
    
    namespace HubBackend
    {
        class Program
        {
            private static IConfiguration Configuration { get; set; }
            static void Main(string[] args)
            {
                //IHostBuilder是供库和应用程序初始化、生成和运行主机的主要组件:
                //就认为是启动的地基,一切都在HostBuildr上面建立起来,
                //Host主机,Builder 建设
                var buildr = new HostBuilder();
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //获取环境变量 //var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); //加载配置文件ConfigurationBuilder 这个写法,可以参考:https://www.jianshu.com/p/b9416867e6e6 var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) //.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //配置sb buildr.ConfigureWebJobs((h, b) => { b.AddAzureStorageCoreServices(); b.AddServiceBus(c => { c.ConnectionString = h.Configuration.GetConnectionString("acc_azure"); c.MessageHandlerOptions.MaxConcurrentCalls = 1; }); } );
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //加入该句会把执行过程中的语句在控制台输出 buildr.ConfigureLogging((context, b) => { b.AddConsole(); });
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //h是HostBuilderContext,也可以理解成上下文,这个上下文是主机Host与数据仓库与Configuration配置文件做交互 //services是IServiceCollection //配置服务(就是配置数据库,Service等等) buildr.ConfigureServices((h, services) => { Configuration = h.Configuration; services.AddOptions();
    //绑定数据库hub string hub = h.Configuration.GetConnectionString("hub"); services.AddDbContext<HUBContext> ( p => p.UseSqlServer(hub) ); services.AddHttpClient(); //配置生命周期 services.AddTransient<HubService.SO>(); services.AddTransient<HubService.Inventory>(); services.AddSingleton(Configuration); services.AddSingleton<HubDatetime.IStandardDateTime, HubDatetime.StandardDateTime>(); });
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //HostBuilder 组建起来了,"变形金刚要站起来"了,Build(); var host = buildr.Build(); using (host) { host.Run();//运行程序 } } } }
    人各有命,上天注定,有人天生为王,有人落草为寇。脚下的路,如果不是你自己的选择,那么旅程的终点在哪,也没人知道。你会走到哪,会遇到谁,都不一定。
  • 相关阅读:
    C#编程总结(三)线程同步 多线程
    配置 Spring.NET
    C# Redis
    WPF MvvmLight RelayCommand 绑定Command 的使用
    WCF编程系列(一)初识WCF
    C#/WPF程序开机自动启动
    C# 创建Windows Service(Windows服务)程序
    前端Js框架汇总
    列式存储和行式存储
    llvm-3.4.2 编译失败 解决方案
  • 原文地址:https://www.cnblogs.com/ZkbFighting/p/13571565.html
Copyright © 2011-2022 走看看