你是不是羨慕Java SpringBoot里功能強大的@注解功能,Spring Boot倡導是一種開箱即用、方便快捷、約定優于配置的開發流程,雖然現在.NET Core也往相同的方向走,但在使用上總有點別扭,目前市面上貌似還沒有輕量級的真正意義上的開箱即用的基于.NET Core的框架,
想想多年前自己開發基于配置的DevFx開發框架,因為需要配置,造成開發人員苦不堪言,而且還容易配置錯誤,導致各種奇怪的錯誤;于是便有全新重寫DevFx框架的想法,經過N個月的奮戰,終于可以放出來用了,
框架不求功能全面,只求使用方便、靈活,
目前框架提供基于Attribute的IoC DI容器,完全可以面向介面編程了;提供輕量級的業務引數配置方案,未來計劃作為集中配置的基礎;提供極簡但不失靈活的資料訪問框架,類似mybatis基于sql的資料訪問;還有基于HTTP/JSON的遠程呼叫方案(以優雅的本地呼叫方式來遠程呼叫);主要是以上幾個功能,
框架是基于.NET Standard 2.0開發,理論上.NET Framework 4.6.1也能使用,因為框架已完全重新重寫了,命名空間啥的都有改變,所以不兼容之前的版本,目前版本是5.0.2,
OK,show me the code,下面讓我們來快速入門,看看怎么個開箱即用,
打開VS2019,建立基于.NET Core 2.2或3.0的控制臺專案ConsoleApp1,下面的例子是基于.NET Core 3.0的,使用NuGet安裝DevFx 5.0.2版本

上圖,忽略DevFx.*,這是老舊版本,目前基于.NET Standard只有一個包,就是DevFx
創建業務邏輯介面和實作類
using DevFx; namespace ConsoleApp1 { //業務邏輯介面,[Service]特性告訴DevFx這個介面需要被DI [Service] public interface IMyService { string GetUserName(string userId); } }
using DevFx; using System; namespace ConsoleApp1 { //業務邏輯實作類,[Object]特性告訴DevFx這個類需要放入到IoC容器里,DevFx會掃描這個類實作了哪些介面,并做映射 [Object] internal class MyService : IMyService { public string GetUserName(string userId) { return $"{userId}_{DateTime.Now.Ticks}"; } } }
開始呼叫邏輯
using DevFx; using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //控制臺程式需要顯式呼叫框架的初始化方法 //ASP.NET Core(通用主機)可以使用UseDevFx擴展方法來初始化框架 ObjectService.Init(); //獲取介面實作類的實體 var myservice = ObjectService.GetObject<IMyService>(); Console.WriteLine(myservice.GetUserName("IamDevFx")); //還能直接獲取MyService類的實體 var myservice1 = ObjectService.GetObject<MyService>(); //2種方式獲取的實體是同一個 Console.WriteLine($" myservice={myservice.GetHashCode()}{Environment.NewLine}myservice1={myservice1.GetHashCode()}"); } } }
運行下:

是不是很簡單?開箱即用!
接下介紹下自動裝配的例子
我們建立另外一個業務邏輯介面和相應的實作類,同樣分別標上[Service]和[Object]
using DevFx; namespace ConsoleApp1 { [Service] public interface IBizService { string GetUserDisplayName(string userId); } [Object] internal class BizService : IBizService { public string GetUserDisplayName(string userId) { return "IamBizService"; } } }
改下之前的業務類MyService
using DevFx; using System; namespace ConsoleApp1 { //業務邏輯實作類,[Object]特性告訴DevFx這個類需要放入到IoC容器里,DevFx會掃描這個類實作了哪些介面,并做映射 [Object] internal class MyService : IMyService { //自動裝配(注入) [Autowired] protected IBizService BizService { get; set; } public string GetUserName(string userId) { return $"{userId}_{DateTime.Now.Ticks}_{this.BizService.GetUserDisplayName(userId)}"; } } }
運行下:

接下來介紹下基于xml的配置,可能有些同學會問,.NET Core不是自帶配置了么?別急,看下我們的使用方式你就清楚誰便捷了,
業務引數指的比如微信的API介面地址、APPID等程式里需要使用的,或者一些開關之類的引數
首先定義需要承載業務引數的介面
using DevFx.Configuration; namespace ConsoleApp1 { //定義需要承載業務引數的介面,[SettingObject("~/myservice/weixin")]告訴框架這是一個配置承載物件 // 其中~/myservice/weixin為配置在組態檔里的路徑 [SettingObject("~/myservice/weixin")] public interface IWeixinSetting { string ApiUrl { get; } string AppID { get; } string AppKey { get; } } }
使用自動裝配特性,裝配到業務邏輯里,我們修改下MyService類
using DevFx; using System; namespace ConsoleApp1 { //業務邏輯實作類,[Object]特性告訴DevFx這個類需要放入到IoC容器里,DevFx會掃描這個類實作了哪些介面,并做映射 [Object] internal class MyService : IMyService { //自動裝配(注入) [Autowired] protected IBizService BizService { get; set; } //配置自動注入 [Autowired] protected IWeixinSetting WeixinSetting { get; set; } public string GetUserName(string userId) { return $"{userId}_{DateTime.Now.Ticks}_{this.BizService.GetUserDisplayName(userId)}_weixin={this.WeixinSetting.ApiUrl}"; } } }
在專案里添加app.config,并設定為有更新就輸出

app.config內容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <devfx> <myservice> <weixin apiUrl="https://api.weixin.qq.com/sns/oauth2/access_token" appId="1234567890" appKey="0123456789" /> </myservice> </devfx> </configuration>
運行下:

最后介紹下類似mybatis的資料訪問是如何開箱即用的,因為涉及到資料庫,稍微復雜些,但還是很方便的,
我們以操作MySql為例,首先需要使用NuGet安裝MySql驅動包,目前框架默認使用社區版的MySql驅動:MySqlConnector

定義我們的資料訪問層介面
using ConsoleApp1.Models; using DevFx; using DevFx.Data; namespace ConsoleApp1.Data { //定義資料操作介面,[DataService]告訴框架這是一個資料操作介面 [DataService(GroupName = "MyService")] public interface IMyDataService : ISessionDataService { EventMessage GetEventMessageByID(string id); } }
在專案中,添加一個.sqlconfig檔案,用來撰寫對應的Sql陳述句,并把這個檔案按嵌入資源形式設定

sqlconfig內容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <devfx> <data> <statements name="MyService"> <add name="GetEventMessageByID"> <sql> <![CDATA[SELECT * FROM EventMessages WHERE MessageGuid = @ID]]> </sql> </add> </statements> </data> </devfx> </configuration>
相信聰明的你能看出對應關系
然后就是在app.config里配置鏈接字串,如下
<?xml version="1.0" encoding="utf-8" ?> <configuration> <devfx> <data debug="true"> <connectionStrings> <add name="EventMessageConnection" connectionString="Database=EventMessages;Data Source=資料庫IP;User ID=資料庫用戶;Password=密碼;Character Set=utf8" providerName="System.Data.MySqlClient" /> </connectionStrings> <dataStorages defaultStorage="EventMessageStorage"> <add name="EventMessageStorage" connectionName="EventMessageConnection" type="MySql" /> </dataStorages> </data> <myservice> <weixin apiUrl="https://api.weixin.qq.com/sns/oauth2/access_token" appId="1234567890" appKey="0123456789" /> </myservice> </devfx> </configuration>
調整下我們MySerivce類
using ConsoleApp1.Data; using DevFx; using System; namespace ConsoleApp1 { //業務邏輯實作類,[Object]特性告訴DevFx這個類需要放入到IoC容器里,DevFx會掃描這個類實作了哪些介面,并做映射 [Object] internal class MyService : IMyService { //自動裝配(注入) [Autowired] protected IBizService BizService { get; set; } //配置自動注入 [Autowired] protected IWeixinSetting WeixinSetting { get; set; } //資料訪問介面自動注入 [Autowired] protected IMyDataService MyDataService { get; set; } public string GetUserName(string userId) { var msg = this.MyDataService.GetEventMessageByID("0000e69f407a4b69bbf3866a499a2eb6"); var str = $"EventMessage:{msg.MessageGuid}_{msg.Category}_{msg.Priority}_{msg.CreatedTime}"; return $"{userId}_{DateTime.Now.Ticks}_{this.BizService.GetUserDisplayName(userId)}_weixin={this.WeixinSetting.ApiUrl}{Environment.NewLine}{str}"; } } }
運行下:

當然資料訪問不僅僅是查詢,還應該有CRUD、分頁以及事務才完整,這些后續會詳細展開,
OK,上面就是這些核心功能的展示,另外框架還支持自定義Attribute的處理方便自行擴展,
后續會比較詳細介紹實作原理以及對框架的拓展,比如服務注冊發現、配置中心等等,
有興趣的同學可以一起共同討論維護,專案開源地址在:https://github.com/mer2/devfx
碼字不容易啊,感興趣的可以去star下,
示例代碼在此:https://files.cnblogs.com/files/R2/ConsoleApp1.zip
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/114293.html
標籤:.NET Core
上一篇:ASP.NET Core 3.0 原生DI拓展實作IocManager
下一篇:.NET Core簡介
