首页 > 其他分享 >webapplication.createBuilder一些记录

webapplication.createBuilder一些记录

时间:2023-05-27 17:12:03浏览次数:57  
标签:null string settings 记录 new webapplication Configuration createBuilder public

internal WebApplicationBuilder(WebApplicationOptions options, Action<IHostBuilder>? configureDefaults = null)
    {
        var configuration = new ConfigurationManager();
 
        configuration.AddEnvironmentVariables(prefix: "ASPNETCORE_");
 
        _hostApplicationBuilder = new HostApplicationBuilder(new HostApplicationBuilderSettings
        {
            Args = options.Args,
            ApplicationName = options.ApplicationName,
            EnvironmentName = options.EnvironmentName,
            ContentRootPath = options.ContentRootPath,
            Configuration = configuration,
        });
 
        // Set WebRootPath if necessary
        if (options.WebRootPath is not null)
        {
            Configuration.AddInMemoryCollection(new[]
            {
                new KeyValuePair<string, string?>(WebHostDefaults.WebRootKey, options.WebRootPath),
            });
        }
 
        // Run methods to configure web host defaults early to populate services
        var bootstrapHostBuilder = new BootstrapHostBuilder(_hostApplicationBuilder);
 
        // This is for testing purposes
        configureDefaults?.Invoke(bootstrapHostBuilder);
 
        bootstrapHostBuilder.ConfigureWebHostDefaults(webHostBuilder =>
        {
            // Runs inline.
            webHostBuilder.Configure(ConfigureApplication);
 
            webHostBuilder.UseSetting(WebHostDefaults.ApplicationKey, _hostApplicationBuilder.Environment.ApplicationName ?? "");
            webHostBuilder.UseSetting(WebHostDefaults.PreventHostingStartupKey, Configuration[WebHostDefaults.PreventHostingStartupKey]);
            webHostBuilder.UseSetting(WebHostDefaults.HostingStartupAssembliesKey, Configuration[WebHostDefaults.HostingStartupAssembliesKey]);
            webHostBuilder.UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey, Configuration[WebHostDefaults.HostingStartupExcludeAssembliesKey]);
        },
        options =>
        {
            // We've already applied "ASPNETCORE_" environment variables to hosting config
            options.SuppressEnvironmentConfiguration = true;
        });
 
        // This applies the config from ConfigureWebHostDefaults
        // Grab the GenericWebHostService ServiceDescriptor so we can append it after any user-added IHostedServices during Build();
        _genericWebHostServiceDescriptor = bootstrapHostBuilder.RunDefaultCallbacks();
 
        // Grab the WebHostBuilderContext from the property bag to use in the ConfigureWebHostBuilder. Then
        // grab the IWebHostEnvironment from the webHostContext. This also matches the instance in the IServiceCollection.
        var webHostContext = (WebHostBuilderContext)bootstrapHostBuilder.Properties[typeof(WebHostBuilderContext)];
        Environment = webHostContext.HostingEnvironment;
 
        Host = new ConfigureHostBuilder(bootstrapHostBuilder.Context, Configuration, Services);
        WebHost = new ConfigureWebHostBuilder(webHostContext, Configuration, Services);
    }

先看下WebApplicationOptions的源码:

namespace Microsoft.AspNetCore.Builder;
 
/// <summary>
/// Options for configuring the behavior for <see cref="WebApplication.CreateBuilder(WebApplicationOptions)"/>.
/// </summary>
public class WebApplicationOptions
{
    /// <summary>
    /// The command line arguments.
    /// </summary>
    public string[]? Args { get; init; }
 
    /// <summary>
    /// The environment name.
    /// </summary>
    public string? EnvironmentName { get; init; }
 
    /// <summary>
    /// The application name.
    /// </summary>
    public string? ApplicationName { get; init; }
 
    /// <summary>
    /// The content root path.
    /// </summary>
    public string? ContentRootPath { get; init; }
 
    /// <summary>
    /// The web root path.
    /// </summary>
    public string? WebRootPath { get; init; }
}

看下:

var configuration = new ConfigurationManager();

源码如下:

public ConfigurationManager()
        {
            _sources = new ConfigurationSources(this);
            _properties = new ConfigurationBuilderProperties(this);
 
            // Make sure there's some default storage since there are no default providers.
            _sources.Add(new MemoryConfigurationSource());
        }

第二步:生成BootstrapHostBuilder, 参数HostApplicationBuilder,是从上面实例化时传递过来的。

public BootstrapHostBuilder(HostApplicationBuilder builder)
    {
        _builder = builder;
 
        foreach (var descriptor in _builder.Services)
        {
            if (descriptor.ServiceType == typeof(HostBuilderContext))
            {
                Context = (HostBuilderContext)descriptor.ImplementationInstance!;
                break;
            }
        }
 
        if (Context is null)
        {
            throw new InvalidOperationException($"{nameof(HostBuilderContext)} must exist in the {nameof(IServiceCollection)}");
        }
    }

 

namespace Microsoft.Extensions.Hosting
{
    /// <summary>
    /// A builder for hosted applications and services which helps manage configuration, logging, lifetime and more.
    /// </summary>
    public sealed class HostApplicationBuilder
    {
        private readonly HostBuilderContext _hostBuilderContext;
        private readonly ServiceCollection _serviceCollection = new();
        private readonly IHostEnvironment _environment;
        private readonly LoggingBuilder _logging;
 
        private Func<IServiceProvider> _createServiceProvider;
        private Action<object> _configureContainer = _ => { };
        private HostBuilderAdapter? _hostBuilderAdapter;
 
        private IServiceProvider? _appServices;
        private bool _hostBuilt;

     /// <summary>
        /// Initializes a new instance of the <see cref="HostApplicationBuilder"/>.
        /// </summary>
        /// <param name="settings">Settings controlling initial configuration and whether default settings should be used.</param>
        public HostApplicationBuilder(HostApplicationBuilderSettings? settings)
        {
            settings ??= new HostApplicationBuilderSettings();
            Configuration = settings.Configuration ?? new ConfigurationManager();
 
            if (!settings.DisableDefaults)
            {
                if (settings.ContentRootPath is null && Configuration[HostDefaults.ContentRootKey] is null)
                {
                    HostingHostBuilderExtensions.SetDefaultContentRoot(Configuration);
                }
 
                Configuration.AddEnvironmentVariables(prefix: "DOTNET_");
            }
 
            Initialize(settings, out _hostBuilderContext, out _environment, out _logging);
 
            ServiceProviderOptions? serviceProviderOptions = null;
            if (!settings.DisableDefaults)
            {
                HostingHostBuilderExtensions.ApplyDefaultAppConfiguration(_hostBuilderContext, Configuration, settings.Args);
                HostingHostBuilderExtensions.AddDefaultServices(_hostBuilderContext, Services);
                serviceProviderOptions = HostingHostBuilderExtensions.CreateDefaultServiceProviderOptions(_hostBuilderContext);
            }
 
            _createServiceProvider = () =>
            {
                // Call _configureContainer in case anyone adds callbacks via HostBuilderAdapter.ConfigureContainer<IServiceCollection>() during build.
                // Otherwise, this no-ops.
                _configureContainer(Services);
                return serviceProviderOptions is null ? Services.BuildServiceProvider() : Services.BuildServiceProvider(serviceProviderOptions);
            };
        }
      private void Initialize(HostApplicationBuilderSettings settings, out HostBuilderContext hostBuilderContext, out IHostEnvironment environment, out LoggingBuilder logging)
        {
            // Command line args are added even when settings.DisableDefaults == true. If the caller didn't want settings.Args applied,
            // they wouldn't have set them on the settings.
            HostingHostBuilderExtensions.AddCommandLineConfig(Configuration, settings.Args);
 
            // HostApplicationBuilderSettings override all other config sources.
            List<KeyValuePair<string, string?>>? optionList = null;
            if (settings.ApplicationName is not null)
            {
                optionList ??= new List<KeyValuePair<string, string?>>();
                optionList.Add(new KeyValuePair<string, string?>(HostDefaults.ApplicationKey, settings.ApplicationName));
            }
            if (settings.EnvironmentName is not null)
            {
                optionList ??= new List<KeyValuePair<string, string?>>();
                optionList.Add(new KeyValuePair<string, string?>(HostDefaults.EnvironmentKey, settings.EnvironmentName));
            }
            if (settings.ContentRootPath is not null)
            {
                optionList ??= new List<KeyValuePair<string, string?>>();
                optionList.Add(new KeyValuePair<string, string?>(HostDefaults.ContentRootKey, settings.ContentRootPath));
            }
            if (optionList is not null)
            {
                Configuration.AddInMemoryCollection(optionList);
            }
 
            (HostingEnvironment hostingEnvironment, PhysicalFileProvider physicalFileProvider) = HostBuilder.CreateHostingEnvironment(Configuration);
 
            Configuration.SetFileProvider(physicalFileProvider);
 
            hostBuilderContext = new HostBuilderContext(new Dictionary<object, object>())
            {
                HostingEnvironment = hostingEnvironment,
                Configuration = Configuration,
            };
 
            environment = hostingEnvironment;
 
            HostBuilder.PopulateServiceCollection(
                Services,
                hostBuilderContext,
                hostingEnvironment,
                physicalFileProvider,
                Configuration,
                () => _appServices!);
 
            logging = new LoggingBuilder(Services);
        }
}

看一下这个方法:

internal static (HostingEnvironment, PhysicalFileProvider) CreateHostingEnvironment(IConfiguration hostConfiguration)
{
            var hostingEnvironment = new HostingEnvironment()
            {
                EnvironmentName = hostConfiguration[HostDefaults.EnvironmentKey] ?? Environments.Production,
                ContentRootPath = ResolveContentRootPath(hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory),
            };
 
            string? applicationName = hostConfiguration[HostDefaults.ApplicationKey];
            if (string.IsNullOrEmpty(applicationName))
            {
                // Note GetEntryAssembly returns null for the net4x console test runner.
                applicationName = Assembly.GetEntryAssembly()?.GetName().Name;
            }
 
            if (applicationName is not null)
            {
                hostingEnvironment.ApplicationName = applicationName;
            }
 
            var physicalFileProvider = new PhysicalFileProvider(hostingEnvironment.ContentRootPath);
            hostingEnvironment.ContentRootFileProvider = physicalFileProvider;
 
            return (hostingEnvironment, physicalFileProvider);
}

再看一个封装类:

namespace Microsoft.Extensions.Hosting
{
    /// <summary>
    /// Constants for HostBuilder configuration keys.
    /// </summary>
    public static class HostDefaults
    {
        /// <summary>
        /// The configuration key used to set <see cref="IHostEnvironment.ApplicationName"/>.
        /// </summary>
        public static readonly string ApplicationKey = "applicationName";
 
        /// <summary>
        /// The configuration key used to set <see cref="IHostEnvironment.EnvironmentName"/>.
        /// </summary>
        public static readonly string EnvironmentKey = "environment";
 
        /// <summary>
        /// The configuration key used to set <see cref="IHostEnvironment.ContentRootPath"/>
        /// and <see cref="IHostEnvironment.ContentRootFileProvider"/>.
        /// </summary>
        public static readonly string ContentRootKey = "contentRoot";
    }
}

接下来:

 public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure, Action<WebHostBuilderOptions> configureOptions)
    {
        ArgumentNullException.ThrowIfNull(configure);
 
        return builder.ConfigureWebHost(webHostBuilder =>
        {
            WebHost.ConfigureWebDefaults(webHostBuilder);
 
            configure(webHostBuilder);
        }, configureOptions);
    }
internal static void ConfigureWebDefaults(IWebHostBuilder builder)
    {
        builder.ConfigureAppConfiguration((ctx, cb) =>
        {
            if (ctx.HostingEnvironment.IsDevelopment())
            {
                StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
            }
        });
 
        ConfigureWebDefaultsWorker(
            builder.UseKestrel(ConfigureKestrel),
            services =>
            {
                services.AddRouting();
            });
 
        builder
            .UseIIS()
            .UseIISIntegration();
    }

后续再补。。。

 

标签:null,string,settings,记录,new,webapplication,Configuration,createBuilder,public
From: https://www.cnblogs.com/Insist-Y/p/17436370.html

相关文章

  • Powershell 修改 DNS 记录权限
    执行脚本需要管理员权限,且需要运行的计算机安装AD管理工具。FunctionSet_DNSACL{###$SourceServerisControldestinationServer.param($SouServer,$DstServer)$DNSServer=(Get-ADDomain).PDCEmulator$ZoneNames=(Get......
  • 【React工作记录六十八】ant design一个页面(新增编辑)
     目录前言导语总结前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷导语antdesign锚点组件编辑核......
  • 【React工作记录七十】判断数组对象中是否满足某条件
     目录前言导语 核心代码总结前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷导语歌谣歌谣数组......
  • 【React工作记录六十九】Taro中的轻提示
     目录前言导语代码部分运行结果代码部分运行结果前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷......
  • 获取门禁记录方式-实时获取
    实时获取开启门禁布防,每次门禁有记录产生都会主动发送信息,其中布防的方式有两种,一种是布防后只能开启一个监听,该监听海康的4200软件也在使用,因此建议在使用期间不要开启4200;另一种监听能开启多个,不过感觉这个不靠谱,建议用第一个,毕竟4200都在用。注意:使用实时获取时,人员编号不要......
  • MySQL刷题记录
    1. select*fromemployeesorderbyhire_datedesclimit1; 笔记: limit 0,1;使用limit关键字从第0条记录向后读取一个,也就是第一条记录  2.select*fromtestLIMIT 3OFFSET 1;(在mysql 5以后支持这种写法)当limit和offset组合使用的时候,limit后面只......
  • 记录--前端小票打印、网页打印
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 一、小票打印目前市面上的小票打印机大多采用的打印指令集为ESC/POS指令,它可以使用ASCII码、十进制、十六进制来控制打印,我们可以使用它来控制字体大小、打印排版、字体加粗、下划线、走纸、切纸、控制钱箱等,下面......
  • 【React工作记录六十六】ant design Row col样式修改
     目录前言导语运行结果前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷导语antdesignRowcol样......
  • 【React工作记录六十七】前端实现复制文字操作
     目录前言导语 核心代码前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从头再来歌谣的意志是永恒的放弃很容易但是坚持一定很酷导语前端实现复制文字操......
  • 获取门禁记录方式-主动获取
    主动获取类似于获取门禁记录,通过代入的查询条件获取范围内的记录信息,使用该方式时需要注意时间范围不要重复或者获取数据后有查重操作,否则会出现重复的情况。流程中的1,2,6,7的代码请参见《获取门禁记录方式-公用方法》流程NET_DVR_Init(初始化)NET_DVR_Login_V40(登录获得Us......