ASP.NET Core 中間件(Middleware)的使用及其源碼解析(三)- 對中間件管道進行分支

来源:https://www.cnblogs.com/xyh9039/archive/2022/08/11/16492284.html
-Advertisement-
Play Games

如果業務邏輯比較簡單的話,一條主管道就夠了,確實用不到分支管道。不過當業務邏輯比較複雜的時候,有時候我們可能希望根據情況的不同使用特殊的一組中間件來處理 HttpContext。這種情況下如果只用一條管道,處理起來會非常麻煩和混亂。此時就可以使用 Map/MapWhen/UseWhen 建立一個分支 ...


如果業務邏輯比較簡單的話,一條主管道就夠了,確實用不到分支管道。不過當業務邏輯比較複雜的時候,有時候我們可能希望根據情況的不同使用特殊的一組中間件來處理 HttpContext。這種情況下如果只用一條管道,處理起來會非常麻煩和混亂。此時就可以使用 Map/MapWhen/UseWhen 建立一個分支管道,當條件符合我們的設定時,由這個分支管道來處理 HttpContext。使用 Map/MapWhen/UseWhen 添加分支管道是很容易的,只要提供合適跳轉到分支管道的判斷邏輯,以及分支管道的構建方法就可以了。

一、對中間件管道進行分支

廢話不多說,我們直接通過一個Demo來看一下如何對中間件管道進行分支,如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using NETCoreMiddleware.Middlewares;

namespace NETCoreMiddleware
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        //服務註冊(往容器中添加服務)
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        /// <summary>
        /// 配置Http請求處理管道
        /// Http請求管道模型---就是Http請求被處理的步驟
        /// 所謂管道,就是拿著HttpContext,經過多個步驟的加工,生成Response,這就是管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region 環境參數

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            #endregion 環境參數

            //靜態文件中間件
            app.UseStaticFiles();

            #region 創建管道分支

            //Map管道分支
            app.Map("/map1", HandleMapTest1);
            app.Map("/map2", HandleMapTest2);

            //MapWhen管道分支
            app.MapWhen(context => context.Request.Query.ContainsKey("mapwhen"), HandleBranch);

            //UseWhen管道分支
            //UseWhen 與 MapWhen 不同的是,如果這個分支不發生短路或包含終端中間件,則會重新加入主管道
            app.UseWhen(context => context.Request.Query.ContainsKey("usewhen"), HandleBranchAndRejoin);

            #endregion 創建管道分支

            #region Use中間件

            //中間件1
            app.Use(next =>
            {
                Console.WriteLine("middleware 1");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine("===================================Middleware===================================");
                        Console.WriteLine($"This is middleware 1 Start");
                    });
                    await next.Invoke(context);
                    await Task.Run(() =>
                    {
                        Console.WriteLine($"This is middleware 1 End");
                        Console.WriteLine("===================================Middleware===================================");
                    });
                };
            });

            //中間件2
            app.Use(next =>
            {
                Console.WriteLine("middleware 2");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 Start"));
                    await next.Invoke(context); //可通過不調用 next 參數使請求管道短路
                    await Task.Run(() => Console.WriteLine($"This is middleware 2 End"));
                };
            });

            //中間件3
            app.Use(next =>
            {
                Console.WriteLine("middleware 3");
                return async context =>
                {
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 Start"));
                    await next.Invoke(context);
                    await Task.Run(() => Console.WriteLine($"This is middleware 3 End"));
                };
            });

            //中間件4
            //Use方法的另外一個重載
            app.Use(async (context, next) =>
            {
                await Task.Run(() => Console.WriteLine($"This is middleware 4 Start"));
                await next();
                await Task.Run(() => Console.WriteLine($"This is middleware 4 End"));
            });

            #endregion Use中間件

            #region UseMiddleware中間件

            app.UseMiddleware<CustomMiddleware>();

            #endregion UseMiddleware中間件

            #region 終端中間件

            //app.Use(_ => handler);
            app.Run(async context =>
            {
                await Task.Run(() => Console.WriteLine($"This is Run"));
            });

            #endregion 終端中間件

            #region 最終把請求交給MVC

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            #endregion 最終把請求交給MVC
        }

        #region 創建管道分支

        /// <summary>
        /// Map管道分支1
        /// </summary>
        /// <param name="app"></param>
        static void HandleMapTest1(IApplicationBuilder app)
        {
            //中間件
            app.Use(next =>
            {
                Console.WriteLine("HandleMapTest1");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleMapTest1 Start");
                    });
                    await next.Invoke(context); //可通過不調用 next 參數使請求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleMapTest1 End"));
                };
            });
        }

        /// <summary>
        /// Map管道分支2
        /// </summary>
        /// <param name="app"></param>
        static void HandleMapTest2(IApplicationBuilder app)
        {
            //中間件
            app.Use(next =>
            {
                Console.WriteLine("HandleMapTest2");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleMapTest2 Start");
                    });
                    await next.Invoke(context); //可通過不調用 next 參數使請求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleMapTest2 End"));
                };
            });
        }

        /// <summary>
        /// MapWhen管道分支
        /// </summary>
        /// <param name="app"></param>
        static void HandleBranch(IApplicationBuilder app)
        {
            //中間件
            app.Use(next =>
            {
                Console.WriteLine("HandleBranch");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleBranch Start");
                    });
                    await next.Invoke(context); //可通過不調用 next 參數使請求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleBranch End"));
                };
            });
        }

        /// <summary>
        /// UseWhen管道分支
        /// </summary>
        /// <param name="app"></param>
        static void HandleBranchAndRejoin(IApplicationBuilder app)
        {
            //中間件
            app.Use(next =>
            {
                Console.WriteLine("HandleBranchAndRejoin");
                return async context =>
                {
                    await Task.Run(() =>
                    {
                        Console.WriteLine("");
                        Console.WriteLine($"This is HandleBranchAndRejoin Start");
                    });
                    await next.Invoke(context); //可通過不調用 next 參數使請求管道短路
                    await Task.Run(() => Console.WriteLine($"This is HandleBranchAndRejoin End"));
                };
            });
        }

        #endregion 創建管道分支
    }
}

下麵我們使用命令行(CLI)方式啟動我們的網站,如下所示:

啟動成功後,我們來訪問一下 “http://localhost:5000/map1/” ,控制台輸出結果如下所示:

訪問 “http://localhost:5000/map2/” ,控制台輸出結果如下所示:

訪問 “http://localhost:5000/home/?mapwhen=1” ,控制台輸出結果如下所示:

訪問 “http://localhost:5000/home/?usewhen=1” ,控制台輸出結果如下所示: 

Map 擴展用作約定來創建管道分支。 Map 基於給定請求路徑的匹配項來創建請求管道分支。 如果請求路徑以給定路徑開頭,則執行分支。

MapWhen 基於給定謂詞的結果創建請求管道分支。 Func<HttpContext, bool> 類型的任何謂詞均可用於將請求映射到管道的新分支。 

UseWhen 也基於給定謂詞的結果創建請求管道分支。 與 MapWhen 不同的是,如果這個分支不發生短路或包含終端中間件,則會重新加入主管道。

二、中間件管道分支源碼解析

下麵我們結合ASP.NET Core源碼來分析下其實現原理: 

1、Map擴展原理

我們將游標移動到 Map 處按 F12 轉到定義,如下所示:

可以發現它是位於 MapExtensions 擴展類中的,我們找到 MapExtensions 類的源碼,如下所示:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder.Extensions;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// Extension methods for the <see cref="MapMiddleware"/>.
    /// </summary>
    public static class MapExtensions
    {
        /// <summary>
        /// Branches the request pipeline based on matches of the given request path. If the request path starts with
        /// the given path, the branch is executed.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param>
        /// <param name="pathMatch">The request path to match.</param>
        /// <param name="configuration">The branch to take for positive path matches.</param>
        /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
        public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (pathMatch.HasValue && pathMatch.Value.EndsWith("/", StringComparison.Ordinal))
            {
                throw new ArgumentException("The path must not end with a '/'", nameof(pathMatch));
            }

            // create branch
            var branchBuilder = app.New();
            configuration(branchBuilder);
            var branch = branchBuilder.Build();

            var options = new MapOptions
            {
                Branch = branch,
                PathMatch = pathMatch,
            };
            return app.Use(next => new MapMiddleware(next, options).Invoke);
        }
    }
}

其中 ApplicationBuilder 類的源碼,如下所示: 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Internal;

namespace Microsoft.AspNetCore.Builder
{
    public class ApplicationBuilder : IApplicationBuilder
    {
        private const string ServerFeaturesKey = "server.Features";
        private const string ApplicationServicesKey = "application.Services";

        private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>();

        public ApplicationBuilder(IServiceProvider serviceProvider)
        {
            Properties = new Dictionary<string, object>(StringComparer.Ordinal);
            ApplicationServices = serviceProvider;
        }

        public ApplicationBuilder(IServiceProvider serviceProvider, object server)
            : this(serviceProvider)
        {
            SetProperty(ServerFeaturesKey, server);
        }

        private ApplicationBuilder(ApplicationBuilder builder)
        {
            Properties = new CopyOnWriteDictionary<string, object>(builder.Properties, StringComparer.Ordinal);
        }

        public IServiceProvider ApplicationServices
        {
            get
            {
                return GetProperty<IServiceProvider>(ApplicationServicesKey);
            }
            set
            {
                SetProperty<IServiceProvider>(ApplicationServicesKey, value);
            }
        }

        public IFeatureCollection ServerFeatures
        {
            get
            {
                return GetProperty<IFeatureCollection>(ServerFeaturesKey);
            }
        }

        public IDictionary<string, object> Properties { get; }

        private T GetProperty<T>(string key)
        {
            object value;
            return Properties.TryGetValue(key, out value) ? (T)value : default(T);
        }

        private void SetProperty<T>(string key, T value)
        {
            Properties[key] = value;
        }

        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _components.Add(middleware);
            return this;
        }

        public IApplicationBuilder New()
        {
            return new ApplicationBuilder(this);
        }

        public RequestDelegate Build()
        {
            RequestDelegate app = context =>
            {
                // If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened.
                // This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware.
                var endpoint = context.GetEndpoint();
                var endpointRequestDelegate = endpoint?.RequestDelegate;
                if (endpointRequestDelegate != null)
                {
                    var message =
                        $"The request reached the end of the pipeline without executing the endpoint: '{endpoint.DisplayName}'. " +
                        $"Please register the EndpointMiddleware using '{nameof(IApplicationBuilder)}.UseEndpoints(...)' if using " +
                        $"routing.";
                    throw new InvalidOperationException(message);
                }

                context.Response.StatusCode = 404;
                return Task.CompletedTask;
            };

            foreach (var component in _components.Reverse())
            {
                app = component(app);
            }

            return app;
        }
    }
}
Microsoft.AspNetCore.Builder.ApplicationBuilder類源碼

其中 MapMiddleware 類的源碼,如下所示: 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder.Extensions
{
    /// <summary>
    /// Represents a middleware that maps a request path to a sub-request pipeline.
    /// </summary>
    public class MapMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly MapOptions _options;

        /// <summary>
        /// Creates a new instance of <see cref="MapMiddleware"/>.
        /// </summary>
        /// <param name="next">The delegate representing the next middleware in the request pipeline.</param>
        /// <param name="options">The middleware options.</param>
        public MapMiddleware(RequestDelegate next, MapOptions options)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _next = next;
            _options = options;
        }

        /// <summary>
        /// Executes the middleware.
        /// </summary>
        /// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
        /// <returns>A task that represents the execution of this middleware.</returns>
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            PathString matchedPath;
            PathString remainingPath;

            if (context.Request.Path.StartsWithSegments(_options.PathMatch, out matchedPath, out remainingPath))
            {
                // Update the path
                var path = context.Request.Path;
                var pathBase = context.Request.PathBase;
                context.Request.PathBase = pathBase.Add(matchedPath);
                context.Request.Path = remainingPath;

                try
                {
                    await _options.Branch(context);
                }
                finally
                {
                    context.Request.PathBase = pathBase;
                    context.Request.Path = path;
                }
            }
            else
            {
                await _next(context);
            }
        }
    }
}

在前兩篇文章中我們已經介紹過,中間件的註冊和管道的構建都是通過 ApplicationBuilder 進行的。因此要構建一個分支管道,需要一個新的 ApplicationBuilder ,並用它來註冊中間件,構建管道。為了在分支管道中也能夠共用我們在當前 ApplicationBuilder 中註冊的服務(或者說共用依賴註入容器,當然共用的並不止這些),在創建新的 ApplicationBuilder 時並不是直接 new 一個全新的,而是調用當前 ApplicationBuilder 的 New 方法在當前的基礎上創建新的,共用了當前 ApplicationBuilder 的 Properties(其中包含了依賴註入容器)。 

在使用 Map 註冊中間件時我們會傳入一個 Action<IApplicationBuilder> 參數,它的作用就是當我們創建了新的 ApplicationBuilder 後,使用這個方法對其進行各種設置,最重要的就是在新的 ApplicationBuilder 上註冊分支管道的中間件。配置完成後調用分支 ApplicationBuilder 的 Build 方法構建管道,並把第一個中間件保存下來作為分支管道的入口。

在使用 Map 註冊中間件時傳入了一個 PathString 參數,PathString 對象我們可以簡單地認為是 string 。它用於記錄 HttpContext.HttpRequest.Path 中要匹配的區段(Segment)。這個字元串參數結尾不能是“/”。如果匹配成功則進入分支管道,匹配失則敗繼續當前管道。

新構建的管道和用於匹配的字元串保存為 MapOptions 對象,保存了 Map 規則和分支管道的入口。之後構建 MapMiddleware 對象,並把它的 Invoke 方法包裝為 RequestDelegate ,使用當前 ApplicationBuilder 的 Use 方法註冊中間件。

2、MapWhen擴展原理

我們將游標移動到 MapWhen 處按 F12 轉到定義,如下所示:

可以發現它是位於 MapWhenExtensions 擴展類中的,我們找到 MapWhenExtensions 類的源碼,如下所示: 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder.Extensions;


namespace Microsoft.AspNetCore.Builder
{
    using Predicate = Func<HttpContext, bool>;

    /// <summary>
    /// Extension methods for the <see cref="MapWhenMiddleware"/>.
    /// </summary>
    public static class MapWhenExtensions
    {
        /// <summary>
        /// Branches the request pipeline based on the result of the given predicate.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="predicate">Invoked with the request environment to determine if the branch should be taken</param>
        /// <param name="configuration">Configures a branch to take</param>
        /// <returns></returns>
        public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Predicate predicate, Action<IApplicationBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            // create branch
            var branchBuilder = app.New();
            configuration(branchBuilder);
            var branch = branchBuilder.Build();

            // put middleware in pipeline
            var options = new MapWhenOptions
            {
                Predicate = predicate,
                Branch = branch,
            };
            return app.Use(next => new MapWhenMiddleware(next, options).Invoke);
        }
    }
}

其中 MapWhenMiddleware 類的源碼,如下所示: 

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Builder.Extensions
{
    /// 	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 《紅樓夢》作為我國四大名著之一,古典小說的巔峰之作,粉絲量極其龐大,而紅學也經久不衰。所以我們今天通過 Python 來探索下紅樓夢裡那千絲萬縷的人物關係,話不多說,開始整活! 一、準備工作 紅樓夢txt格式電子書一份 金陵十二釵+賈寶玉人物名稱列表 寶玉 nr 黛玉 nr 寶釵 nr 湘雲 nr ...
  • “什麼是IO的多路復用機制?” 這是一道年薪50W的面試題,很遺憾,99%的人都回答不出來。 大家好,我是Mic,一個工作了14年的Java程式員。 今天,給大家分享一道網路IO的面試題。 這道題目的文字回答已經整理到了15W字的面試文檔裡面,大家可以S我領取。 下麵看看高手的回答。 高手: IO多 ...
  • 多商戶商城系統,也稱為B2B2C(BBC)平臺電商模式多商家商城系統。可以快速幫助企業搭建類似拼多多/京東/天貓/淘寶的綜合商城。 多商戶商城系統支持商家入駐加盟,同時滿足平臺自營、旗艦店等多種經營方式。平臺可以通過收取商家入駐費,訂單交易服務費,提現手續費,簡訊通道費等多手段方式,實現整體盈利。 ...
  • 原文連接:https://www.zhoubotong.site/post/67.html Go 標準庫的net/url包提供的兩個函可以直接檢查URL合法性,不需要手動去正則匹配校驗。 下麵可以直接使用ParseRequestURI()函數解析URL,當然這個只會驗證url格式,至於功能變數名稱是否存在或 ...
  • Python帶我起飛——入門、進階、商業實戰_ 免費下載地址 內容簡介 · · · · · · 《Python帶我起飛——入門、進階、商業實戰》針對Python 3.5 以上版本,採用“理論+實踐”的形式編寫,通過大量的實例(共42 個),全面而深入地講解“Python 基礎語法”和“Python ...
  • 1、應用場景 1.1 kafka場景 ​ Kafka最初是由LinkedIn公司採用Scala語言開發,基於ZooKeeper,現在已經捐獻給了Apache基金會。目前Kafka已經定位為一個分散式流式處理平臺,它以 高吞吐、可持久化、可水平擴展、支持流處理等多種特性而被廣泛應用。 ​ Apache ...
  • Redis是大規模互聯網應用常用的記憶體高速緩存資料庫,它的讀寫速度非常快,據官方 Bench-mark的數據,它讀的速度能到11萬次/秒,寫的速度是8.1萬次/秒。 1. 認識Spring Cache 在很多應用場景中通常是獲取前後相同或更新不頻繁的數據,比如訪問產品信息數據、網頁數據。如果沒有使用 ...
  • .NET nanoFramework 安裝教程 準備材料​ esp32單片機(支持wifi藍牙) 安卓數據線(需要支持傳輸) 註意!請先安裝esp32驅動程式​ ESP32驅動鏈接 安裝 .NET nanoFramework固件快閃記憶體​ 安裝工具 dotnet tool install -g nano ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...