Bu makale makine çevirisi ayna makalesidir, orijinal makaleye geçmek için lütfen buraya tıklayın.

Görünüm: 59583|Yanıt: 1

[Kaynak] ASP.NET Core (7) Framework kaynak kodunun derinlemesine analizi

[Bağlantıyı kopyala]
2021-3-24 13:43:28 tarihinde yayınlandı | | |
Eleştiri:

ASP.NET Core (VI) DI, nesneleri enjekte etme yöntemini manuel olarak elde eder
https://www.itsvse.com/thread-9595-1-1.html

ASP.NET Core (beş) CAP dağıtık işlemlere dayanmaktadır
https://www.itsvse.com/thread-9593-1-1.html

ASP.NET Core(4) filtresi birleşik ModelState model validasyonu
https://www.itsvse.com/thread-9589-1-1.html

ASP.NET Core (iii) ActivatorUtilities kullanarak dinamik örnekler oluşturun
https://www.itsvse.com/thread-9488-1-1.html

ASP.NET Çekirdek (2) Uygulamayı kodla yeniden başlat
https://www.itsvse.com/thread-9480-1-1.html

ASP.NET Core (1) Redis önbellekleme kullanır
https://www.itsvse.com/thread-9393-1-1.html
ASP.NET Core GitHub açık kaynak adresini ekleye başlayın

Bağlantı girişi görünür.
Bağlantı girişi görünür.


asp.net Çekirdek kaynak kodu adresi
https://www.itsvse.com/thread-9394-1-1.html


Core 3.1 ASP.NET yeni bir proje oluşturulduktan sonra program kodu şu şekildedir:

Giriş kodu ile GitHub kaynak kodu birleşiklerini derinlemesine inceledik.

Ana Kod:Bağlantı girişi görünür.

CreateDefaultBuilder metodu

Burada, IHostBuilder'dan miras alan bir HostBuilder nesnesi oluşturulur ve :appsettings.json, appsettings gibi sistem tanımlı delegeler ekleriz. {env. EnvironmentName}.json yapılandırma dosyası, sonunda döner: IHostBuilder arayüzü.

HostBuilder Kodu:Bağlantı girişi görünür.

Build yöntemi sonunda çağrılacak.


public IHost Build()
{
    if (_hostBuilt)
    {
        yeni InvalidOperationException(SR. BuildCalled);
    }
    _hostBuilt = doğru;

    BuildHostConfiguration();
    CreateHostingEnvironment();
    CreateHostBuilderContext();
    BuildAppConfiguration();
    CreateServiceProvider();

    geri _appServices.GetRequiredService<IHost>();
}
BuildHostConfiguration method

özel IConfiguration _hostConfiguration;
IConfigurationBuilder configBuilder = yeni ConfigurationBuilder()
Delegeyi çağırarak sırayla yapılandırma ekleyin

CreateHostingEnvironment metodu

özel HostingEnvironment _hostingEnvironment;
_hostingEnvironment = yeni HostingEnvironment()
{
    ApplicationName = _hostConfiguration[HostDefaults.ApplicationKey],
    EnvironmentName = _hostConfiguration[HostDefaults.EnvironmentKey] ?? Ortamlar.Prodüksiyon,
    ContentRootPath = ResolveContentRootPath(_hostConfiguration[HostDefaults.ContentRootKey], AppContext.BaseDirectory),
};
CreateHostBuilderContext method

private HostBuilderContext _hostBuilderContext;
_hostBuilderContext = yeni HostBuilderContext(Properties)
{
    HostingEnvironment = _hostingEnvironment,
    Yapılandırma = _hostConfiguration
};
BuildAppConfiguration yöntemi

Konfigürasyon bilgilerini tekrar entegre edin

IConfigurationBuilder configBuilder = yeni ConfigurationBuilder()
                . SetBasePath(_hostingEnvironment.ContentRootPath)
                . AddConfiguration(_hostConfiguration, shouldDisposeConfiguration: true);
_appConfiguration = configBuilder.Build();
            _hostBuilderContext.Yapılandırma = _appConfiguration;
CreateServiceProvider yöntemi

var services = yeni ServiceCollection();
Bir servis kaydedin, bir temsilciyi çağırın ve kullanıcı tanımlı bir hizmet ekleyin.

GenericHostBuilderExtensions extension method

Bağlantı girişi görünür.

ConfigureWebHost uzantı yöntemi

GenericWebHostService'i bir backend servis olarak kaydetmek için:


Yapımcı. ConfigureServices((context, services) => servis. AddHostedService<GenericWebHostService>());
GenericWebHostService Kodu:Bağlantı girişi görünür.


public async Görev StartAsync(İptalasyonToken iptalToken)
        {
            HostingEventSource.Log.HostStart();

            var serverAddressesFeature = Server.Features.Get<IServerAddressesFeature>();
            var addresses = serverAddressesFeature?. Adresler;
            if (adresler != null && !adresler. IsReadOnly && adresleri. Sayı == 0)
            {
                var urls = Configuration[WebHostDefaults.ServerUrlsKey];
                if (!string. IsNullOrEmpty(urls))
                {
                    serverAdreslerÖzellik!. PreferHostingUrls = WebHostUtilities.ParseBool(Configuration, WebHostDefaults.PreferHostingUrlsKey);

                    foreach (URL'lerde var değeri. Split('; ', StringSplitOptions.RetakeEmptyEntries))
                    {
                        adresler. Toplama(değer);
                    }
                }
            }

            RequestDelegate mi? uygulama = null;

            Denemek
            {
                var configure = Options.ConfigureApplication;

                if (configure == null)
                {
                    throw new InvalidOperationException($"Uygulama konfigurement yok. Lütfen bir uygulamayı IWebHostBuilder.UseStartup, IWebHostBuilder.Configure'den veya {nameof(WebHostDefaults.StartupAssemblyKey)} üzerinden {nameof(WebHostDefaults.StartupAssemblyKey)} üzerinden bir uygulama belirtin web barındırma yapılandırması.");
                }

                var builder = ApplicationBuilderFactory.CreateBuilder(Server.Features);

                foreach (var filter in StartupFilters.Reverse())
                {
                    configure = filtrele. Konfigürasyon (yapılandırma);
                }

                configure(builder);

                İstek boru hattını oluştur
                uygulama = Yapımcı. Build();
            }
            catch (İstisna örneğin)
            {
                Logger.ApplicationError(ex);

                if (! Options.WebHostOptions.CaptureStartupErrors)
                {
                    atmak;
                }

                var showDetailedErrors = HostingEnvironment.IsDevelopment() || Options.WebHostOptions.DetailedErrors;

                application = ErrorPageBuilder.BuildErrorPageApplication(HostingEnvironment.ContentRootFileProvider, Logger, showDetailedErrors, örk);
            }

            var httpApplication = new HostingApplication (application, Logger, DiagnosticListener, HttpContextFactory);

            await Server.StartAsync(httpApplication, cancellationToken);

            if (adresler != null)
            {
                foreach (adreslerde var adresi)
                {
                    LifetimeLogger.ListeningOnAddress(address);
                }
            }

            if (Logger.IsEnabled(LogLevel.Debug))
            {
                foreach (var assembly in Options.WebHostOptions.GetFinalHostingStartupAssemblies())
                {
                    Logger.StartupAssemblyLoaded(assembly);
                }
            }

            if (Options.HostingStartupExceptions != null)
            {
                foreach (var exception in Options.HostingStartupExceptions.InnerExceptions)
                {
                    Logger.HostingStartupAssemblyError(exception);
                }
            }
        }


var webhostBuilder = yeni GenericWebHostBuilder(builder, webHostBuilderOptions);
Bağlantı girişi görünür.

WebHostBuilderExtensions uzantı yöntemi

IWebHostBuilder çağrıları için startupType nesnesi sağlar.

bu IWebHostBuilder hostBuilder
if (hostBuilder ISupportsStartupsStartupsStartup destekliyor)
{
    returnsStartup.UseStartup(startupType);
}
Bağlantı girişi görünür.

GenericWebHostBuilder Private Method GenericWebHostBuilder

Startup nesnemizi dinamik olarak ortaya çıkarmak:

örneğin ?? = ActivatorUtilities.CreateInstance(yeni HostServiceProvider(webHostBuilderContext), startupType);
bağlam. Properties[_startupKey] = örnek;
ConfigureServices yöntemini arayın

var configureServicesBuilder = StartupLoader.FindConfigureServicesDelegate(startupType, context. HostingEnvironment.EnvironmentName);
                var configureServices = configureServicesBuilder.Build(instance);

internal static ConfigureServicesBuilder FindConfigureServicesDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type, string environmentName)
        {
            var servicesMethod = FindMethod(startupType, "Configure{0}Services", environmentName, typeof(IServiceProvider), required: false)
                ?? FindMethod(startupType, "Configure{0}Services", environmentName, typeof(void), gerekli: false);
            yeni ConfigureServicesBuilder(servicesMethod) geri döndür;
ConfigureContainer yöntemini arayın

var configureContainerBuilder = StartupLoader.FindConfigureContainerDelegate(startupType, context. HostingEnvironment.EnvironmentName);

internal static ConfigureContainerBuilder FindConfigureContainerDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, string environmentName)
        {
            var configureMethod = FindMethod(startupType, "Configure{0}Container", environmentName, typeof(void), required: false);
            return new ConfigureContainerBuilder(configureMethod);
        }
Configure yöntemini arayın

configureBuilder = StartupLoader.FindConfigureDelegate(startupType, context. HostingEnvironment.EnvironmentName);

internal static ConfigureBuilder FindConfigureDelegate([DynamicallyAccessedMembers(StartupLinkerOptions.Accessibility)] Type startupType, string environmentName)
{
    var configureMethod = FindMethod(startupType, "Configure{0}", environmentName, typeof(void), required: true)!;
    yeni ConfigureBuilder(configureMethod) geri döndür;
}
ConfigureBuilder'ın Build yöntemiyle çağrılan kaynak kodu şöyledir:

özel sınıf ConfigureBuilder
        {
            public ConfigureBuilder(MethodInfo configure)
            {
                MethodInfo = yapılandırmak;
            }

            public MethodInfo MethodInfo { get; }

            public Action<IApplicationBuilder> Build(object instance)
            {
                return (applicationBuilder) => Invoke(instance, applicationBuilder);
            }

            private void Invoke(object instance, IApplicationBuilder builder)
            {
                var serviceProvider = builder. ApplicationServices;
                var parameterInfos = MethodInfo.GetParameters();
                var parametreleri = yeni nesne[parameterInfos.Length];
                için (var indeksi = 0; index < parameterInfos.Length; index++)
                {
                    var parameterInfo = parameterInfos[index];
                    if (parameterInfo.ParameterType == typeof(IApplicationBuilder))
                    {
                        parametreler[indeks] = oluşturucu;
                    }
                    else
                    {
                        Denemek
                        {
                            parameters[index] = serviceProvider.GetRequiredService(parameterInfo.ParameterType);
                        }
                        catch (İstisna örneğin)
                        {
                            yeni InvalidOperationException(
                                Resources.FormatMiddlewareFilter_ServiceResolutionFail(
                                    parameterInfo.ParameterType.FullName,
                                    parameterInfo.Name,
                                    MethodInfo.Name,
                                    MethodInfo.DeclaringType.FullName),
                                örneğin);
                        }
                    }
                }
                MethodInfo.Invoke(instance, parametreler);
            }
        }
Çalıştırma yöntemi

HostingAbstractionsHostExtensions uzantı yöntemi adresi:

Bağlantı girişi görünür.


Sonunda arar:

/// <summary>
        Bir uygulama çalıştırır ve yalnızca token tetiklendiğinde veya kapatma tetiklendiğinde tamamlanan bir Görev döndürür.
        /// </summary>
        <param name="host"> <bkz. cref="IHost"/> çalıştırmak.</param>
        <param name="token"> Kapanış tetikleyici token.</param>
        <returns><bkz. cref="Görev"/> asenkron işlemi temsil eder.</returns>
        public static async Görev RunAsync(bu IHost hostu, CancellationToken token = varsayılan)
        {
            Denemek
            {
                Ev sahibini bekle. StartAsync(token) ile konuşur. ConfigureAwait (yanlış);

                Ev sahibini bekle. WaitForShutdownAsync(token). ConfigureAwait (yanlış);
            }
            Sonunda
            {
                if (host IAsyncDisposable asyncDisposable ise)
                {
                    asyncDisposable.Dispose Async() bekle. ConfigureAwait (yanlış);
                }
                else
                {
                    Ev sahibi. Disposal();
                }

            }
        }
Daha önce, bir hizmet oluştururken, IHost servisine kaydolurdum ve kod şöyledir:

hizmetler. <IHost>AddSingleton(_ =>
            {
                return new Internal.Host(_appServices,
                    _appServices.GetRequiredService<IHostApplicationLifetime>(),
                    _appServices.GetRequiredService<ILogger<Internal.Host>>(),
                    _appServices.GetRequiredService<IHostLifetime>(),
                    _appServices.GetRequiredService<IOptions<HostOptions>>());
            });
StartAsync yöntemi

Adres:Bağlantı girişi görünür.

public async Görev StartAsync(CancellationToken cancellationToken = default)
        {
            _logger. Starting();

            var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _applicationLifetime.ApplicationStopping) kullanılıyor;
            CancellationToken combinedCancellationToken = combinedCancellationTokenSource.Token;

            _hostLifetime.WaitForStartAsync(combinedCancellationToken) bekle. ConfigureAwait (yanlış);

            combinedCancellationToken.ThrowIfCancellationRequested();
            _hostedServices = Services.GetService<<IHostedService>IEnumerable>();

            foreach (IHostedService hostedService _hostedServices)
            {
                Ateş IHostedService.Başlat
                await hostedService.StartAsync(combinedCancellationToken). ConfigureAwait (yanlış);

                if (hostedService ise BackgroundService backgroundService)
                {
                    _ = HandleBackgroundException(backgroundService);
                }
            }

            Ateş IHostApplicationLifetime.Başlatıldı
            _applicationLifetime.NotifyStarted();

            _logger. Başladı();
        }
(Son)




Önceki:Geç kalan yeni katılımcı raporları
Önümüzdeki:Linux Arıza İşleme uygulama paketinde .NET Core hatası
2021-9-22 tarihinde 20:45:12 tarihinde yayınlandı |
Öğrenmeyi öğren...
Feragatname:
Code Farmer Network tarafından yayımlanan tüm yazılım, programlama materyalleri veya makaleler yalnızca öğrenme ve araştırma amaçları içindir; Yukarıdaki içerik ticari veya yasa dışı amaçlarla kullanılamaz, aksi takdirde kullanıcılar tüm sonuçları ödemelidir. Bu sitedeki bilgiler internetten alınmakta olup, telif hakkı anlaşmazlıklarının bu siteyle hiçbir ilgisi yoktur. Yukarıdaki içeriği indirmeden sonraki 24 saat içinde bilgisayarınızdan tamamen silmelisiniz. Programı beğendiyseniz, lütfen orijinal yazılımı destekleyin, kayıt satın alın ve daha iyi orijinal hizmetler alın. Herhangi bir ihlal olursa, lütfen bizimle e-posta yoluyla iletişime geçin.

Mail To:help@itsvse.com