開箱即用簡單便捷的輕量級開源開發框架


  你是不是羡慕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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM