翻譯|使用教程|編輯:龔雪|2025-05-28 10:13:16.470|閱讀 109 次
概述:本文將為大家介紹DevExpress XAF將.NET Aspire集成到Blazor項目中后如何實現自定義遙測,歡迎下載最新版組件體驗!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
DevExpress XAF是一款強大的現代應用程序框架,允許同時開發ASP.NET和WinForms。DevExpress XAF采用模塊化設計,開發人員可以選擇內建模塊,也可以自行創建,從而以更快的速度和比開發人員當前更強有力的方式創建應用程序。
.NET Aspire是一組工具、模板和包,用于構建可觀察的、可生產的應用程序。DevExpress XAF團隊花費了一些時間考慮Aspire的功能,試圖找到最好的集成點,讓XAF開發人員能夠利用Aspire開箱即用的業務流程特性。
DevExpress技術交流群11:749942875 歡迎一起進群討論
在最近的一篇文章中我們介紹了如何對一個 XAF Blazor 項目進行調整,來支持 .NET Aspire()。通過對啟動邏輯進行一些修改——包括標準的 XAF 項目模板和 Aspire 的 Visual Studio 向導生成的代碼,已經可以讓 XAF Blazor 項目作為 Aspire 編排體系的一部分運行了。但那只是最小規模的編排,只有一個模塊!接下來我們將會把部署方面的內容留到第三篇(敬請關注!),接下來得系列文章將介紹在示例項目中為實現以下三個場景所做的修改:
完整示例項目已托管在這個中。下面基于我在第一篇文章中描述的項目初始狀態,展開說明新的功能實現。
Aspire 儀表盤的集成,是許多應用項目在啟用 Aspire 后最直觀的新特性之一。正如在演示項目的第一步中看到的,啟用默認的跟蹤和指標來源非常簡單。接下來我們就會思考:如何將遙測系統用于我們自己的場景,比如記錄自定義日志、報告業務指標與活動?
第一步,我創建了文件 XafAspireDemo.Blazor.Server/Controllers/ImportantBusinessOperationsController.cs,它實現了一個基本的 XAF 控制器,并提供了一個動作(Action)。該操作會自動出現在用戶界面中,因此可以用作交互式測試觸發器。以下是代碼:
namespace XafAspireDemo.Blazor.Server.Controllers { public class ImportantBusinessOperationsController : Controller { SimpleAction importantBusinessAction; IServiceProvider serviceProvider; public ImportantBusinessOperationsController() { importantBusinessAction = new SimpleAction( this, "ImportantBusinessAction", PredefinedCategory.View ); importantBusinessAction.Execute += ImportantBusinessAction_Execute; } [ActivatorUtilitiesConstructor] public ImportantBusinessOperationsController(IServiceProvider serviceProvider) : this() { this.serviceProvider = serviceProvider; } private async void ImportantBusinessAction_Execute( object sender, SimpleActionExecuteEventArgs e ) { var logger = serviceProvider.GetRequiredService< ILogger<ImportantBusinessOperationsController> >(); importantBusinessAction.Enabled["ImportantBusinessActionRunning"] = false; logger.LogInformation("ImportantBusinessAction started."); try { // This is where we perform the magic for the important business action. // Run a task that waits a random time between half a second and five seconds. await Task.Run(() => { Thread.Sleep(new Random().Next(500, 5000)); }); } catch (Exception ex) { logger.LogError(ex, "ImportantBusinessAction failed."); throw; } finally { importantBusinessAction.Enabled["ImportantBusinessActionRunning"] = true; } } protected override void OnActivated() { base.OnActivated(); var logger = serviceProvider.GetRequiredService< ILogger<ImportantBusinessOperationsController> >(); logger.LogInformation("ImportantBusinessOperationsController activated."); } protected override void OnDeactivated() { var logger = serviceProvider.GetRequiredService< ILogger<ImportantBusinessOperationsController> >(); logger.LogInformation("ImportantBusinessOperationsController deactivated."); base.OnDeactivated(); } } }
如你所見,這段代碼已經加入了日志記錄的邏輯。它使用的是 .NET 提供的標準 ILogger<T> 接口,并結合了構造函數依賴注入(通過 IServiceProvider 獲取服務實例),這是XAF推薦的方式。
ASP.NET Core 的日志基礎設施會自動將這些日志輸出集成到 Aspire 儀表盤中。完成上述更改后,運行程序并點擊Important Business Action按鈕,即可在儀表盤中查看相關日志輸出。按鈕會被隨機禁用一段時間,并在初始化與交互過程開始時輸出日志內容,在儀表盤的“結構化日志(Structured Logs)”頁面即可查看這些信息。
要記錄 OpenTelemetry 的活動(Activity)并使用計量器(Meter),您需要在應用啟動時初始化這些對象,并確保相關代碼能夠訪問到它們。可以通過全局單例模式實現,但在這個示例項目中,更合理的方式是繼續使用依賴注入機制,并讓它來處理生命周期管理。
以下是 XafAspireDemo.Blazor.Server.Telemetry 類的實現:
namespace XafAspireDemo.Blazor.Server { public class Telemetry : IDisposable { public ActivitySource ActivitySource { get; } public Meter Meter { get; } public string MeterName => Meter.Name; public Counter<long> ImportantBusinessOperationCounter { get; } public Histogram<double> ImportantBusinessOperationDuration { get; } public Telemetry( string serviceName = "XafAspireDemo.Blazor.Server", string version = "1.0.0" ) { ActivitySource = new ActivitySource(serviceName, version); Meter = new Meter(serviceName, version); ImportantBusinessOperationCounter = Meter.CreateCounter<long>( "important_business_operation.execution_count" ); ImportantBusinessOperationDuration = Meter.CreateHistogram<double>( "important_business_operation.execution_duration" ); } public void Dispose() { ActivitySource.Dispose(); Meter.Dispose(); } } }
這里的 ActivitySource、Meter、Counter<T> 和 Histogram<T> 類型都來自 System.Diagnostics.Metrics 命名空間。這個類在應用啟動時創建相關對象,在應用結束時自動釋放。
您只需要在 Startup.cs 中注冊該類為單例服務即可:
builder.AddEntityFrameworkCoreInstrumentation(); }); --> var telemetry = new Telemetry(); --> services.AddSingleton(telemetry); --> services --> .AddOpenTelemetry() --> .WithTracing(tracing => tracing.AddSource("XafAspireDemo.Blazor.Server")) --> .WithMetrics(metrics => --> { --> metrics.AddMeter(telemetry.MeterName); --> }); services.AddSingleton( typeof(Microsoft.AspNetCore.SignalR.HubConnectionHandler<>),
接下來我們要將遙測功能應用到前面創建的業務操作中,只需在 ImportantBusinessAction_Execute 方法中添加幾行代碼即可:
private async void ImportantBusinessAction_Execute( object sender, SimpleActionExecuteEventArgs e ) { --> var telemetry = serviceProvider.GetRequiredService<Telemetry>(); var logger = serviceProvider.GetRequiredService< ILogger<ImportantBusinessOperationsController> >(); importantBusinessAction.Enabled["ImportantBusinessActionRunning"] = false; --> using var activity = telemetry.ActivitySource.StartActivity("ImportantBusinessAction"); logger.LogInformation("ImportantBusinessAction started."); try { ... } catch (Exception ex) { logger.LogError(ex, "ImportantBusinessAction failed."); --> activity?.SetStatus(ActivityStatusCode.Error); --> activity?.AddException(ex); throw; } finally { --> activity?.Stop(); importantBusinessAction.Enabled["ImportantBusinessActionRunning"] = true; --> telemetry.ImportantBusinessOperationCounter.Add(1); --> telemetry.ImportantBusinessOperationDuration.Record( --> activity.Duration.TotalMilliseconds --> ); } }
在方法開始處,我們通過依賴注入獲取遙測服務,然后開啟一個活動(Activity)。如果執行過程中發生錯誤,會記錄異常信息,并將活動狀態設為錯誤,最后記錄計數器和直方圖的相關指標值。
這樣,當您執行該業務操作時,Aspire 儀表盤便能顯示相應的指標與活動信息。值得注意的是,OpenTelemetry 會自動關聯活動與指標(如執行時長記錄),不需要你手動建立連接。
未完待續,我們下期再見!更多產品資訊及授權,歡迎來電咨詢:023-68661681
慧都是?家?業數字化解決?案公司,專注于軟件、?油與?業領域,以深?的業務理解和?業經驗,幫助企業實現智能化轉型與持續競爭優勢。
慧都科技是DevExpress的中國區的合作伙伴,DevExpress作為用戶界面領域的優秀產品,幫助企業高效構建權限管理、數據可視化(如網格/圖表/儀表盤)、跨平臺系統(WinForms/ASP.NET/.NET MAUI)及行業定制解決方案,加速開發并強化交互體驗。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都網