ASP.NET Core+MongoDB(一)


項目類庫:.Net Standar 2.0
web:ASP.NET CORE 2.2 版本

 

先上圖,看我們的解決方案結構:

 

分別對上面的工程進行說明:
1、KYSharpCore:為公共的基礎類,最底層

2、KYSharpCore.MongoDB:為公共的MongoDB操作基類

3、DPMS.Model :為demo的實體層/

4、DPMS.Repository:為demo的倉儲層/

5、DPMS.Service:為demo的服務層

6、DPMS.Web:為demo的web層項目,MVC框架

KYSharpCore.NPOI:為導出組件,該組件與上面不存在層級關系,為獨立的功能組件。

以上工程,必須遵循固定的順序進行引用,即12345的順序。

因為1和2是基礎類,我們這邊不做贅述,將在其他章節中講述。我們從3開始講起

 

約定:公共的類庫,我們選擇.NET Standar 2.0作為目標框架。可與framework進行共享。

本demo的倉儲層、服務層、model層均為 Standar 2.0框架建設。

一、實體層

 

因為是使用MongoDB,需要引用MongoDB.Bson.

Nuget上引用:

 

1、創建一個實體基類EntityBase,設置公共字段

namespace DPMS.Model
{
   public class EntityBase
    {
        /// <summary>
        /// MongoDB系統自帶的主鍵
        /// </summary>
        [Key]
        public ObjectId _id { get; set; }

        /// <summary>
        /// 用於接收自增的數字ID
        /// </summary>
        public int ID { get;set;}

        /// <summary>
        /// 添加時間
        /// </summary>
        public DateTime AddTime { get; set; } = DateTime.Now;
    }
}

 

2、新建一個需求實體 Invest

namespace DPMS.Model
{
    /// <summary>
    /// 需求表
    /// </summary>
  public  class Invest:EntityBase
    {
        /// <summary>
        /// 團隊代碼
        /// </summary>
        public string TeamCode { get; set; }

        /// <summary>
        /// 團隊負責人 拼音,與企業微信一致
        /// </summary>
        public string TeamLeader { get; set; }

        /// <summary>
        /// 禪道-需求編號
        /// </summary>
        public string CD_No { get; set; }

        /// <summary>
        /// 禪道-歸屬產品名稱
        /// </summary>
        public string CD_Product { get; set; }

        /// <summary>
        /// 禪道-需求標題
        /// </summary>
        public string CD_Title { get; set; }

        /// <summary>
        /// 需求發布者,產品經理
        /// </summary>
        public string Producter { get; set; }

        /// <summary>
        /// 產品經理名稱
        /// </summary>
        public string ProducterName { get; set; }

        /// <summary>
        /// SM確認的狀態  0:無  1:按時完成  2:完成但延時 3:非本月需完成 4:未完成
        /// </summary>
        public int SM_Status { get; set; } = 0;

        /// <summary>
        /// 產品經理確認的狀態
        /// </summary>
        public int Pro_Status { get; set; } = 0;

        /// <summary>
        /// 歸屬月份,格式YYYYMM,201906
        /// </summary>
        public string Month { get; set; }
    }
}

demo中的實體就這樣了

二、倉儲層

 

倉儲層需要引用KYSharpCore和KYSharpCore.MongoDB 兩個基類,以及Model層

為什么選擇用倉儲,原因很簡單,方便我們進行個性化擴展。在數據操作的底層進行其他個性化邏輯處理。

約定:

1、接口的定義放在根目錄下,接口的實現類,統一放到Impl文件夾,表示實現類目錄。

2、每個實體,對應一個倉儲的接口和實現類,即有多少個實體,就對應創建多少個接口和實現類。

我們新建一個Invest的倉儲接口 IInvestRepository.cs

namespace DPMS.Repository
{
    public interface IInvestRepository:IRepository<Invest>
    {
    }
}

繼承了KYSharpCore.MongoDB中的倉儲接口

接着在Impl中新建一個Invest的倉儲實現InvestRepository.cs

namespace DPMS.Repository.Impl
{
   public class InvestRepository:Repository<Invest>,IInvestRepository
    {
        public InvestRepository(DbContextBase dbContext) : base(dbContext)
        {
        }

    }
}

該實現同時繼承KYSharpCore.MongoDB中的倉儲實現類,以及invest的接口。此時,InvestRepository就已經實現了各種關於MongoDB增刪改查的的基礎方法。

 大家會發現,倉儲層構造函數是帶參數的,需要有DbContextBase,此為數據庫上下文對象。所以在web端,需要對數據庫上下文進行注入。下面web內容會講。

三、服務層

服務層在倉儲層基礎上,增加倉儲層的引用。

服務層與倉儲層類似,它屬於藏儲層的使用者。定義的方式與藏儲層類似,有接口和Impl實現目錄。

但服務層不需要一個實體對應一個,服務層更多的是按照功能模塊的划分,比如 一個登錄模塊,創建一個LoginService。

為了模擬,我們這里做個簡單的添加功能而已。

namespace DPMS.Service
{
    /// <summary>
    /// 需求模塊服務接口
    /// </summary>
   public interface IInvestService
   {
       /// <summary>
       /// 添加需求
       /// </summary>
       /// <param name="model"></param>
       /// <returns></returns>
       string AddInvest(Invest model);
       /// <summary>
       /// 獲取配置信息
       /// </summary>
       /// <returns></returns>
       string GetName();

   }
}

 

namespace DPMS.Service.Impl
{
    /// <summary>
    /// 需求實現類
    /// </summary>
    public class InvestService : IInvestService
    {
   
        private readonly IInvestRepository _investRepository; //需求的倉儲
        private readonly IConfiguration _configuration;//全局的配置對象

        /// <summary>
        /// 在構造函數中注入
        /// </summary>
        /// <param name="investRepository"></param>
        /// <param name="configuration"></param>
        public InvestService(IInvestRepository investRepository, IConfiguration configuration)
        {
            _investRepository = investRepository;
            _configuration = configuration;
        }
        /// <summary>
        /// 添加需求
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string AddInvest(Invest model)
        {
            _investRepository.Add(model); //注意這里的_investRepository為接口對象
            return model.ID.ToString();
        }

        /// <summary>
        /// 獲取appsettings.json中的配置信息,此例是演示如何讀取配置
        /// </summary>
        /// <returns></returns>
        public string GetName()
        {
           return _configuration.GetSection("AllowedHosts").Key+":"+_configuration.GetSection("AllowedHosts").Value;
        }
    }
}

 

 

 四、Web層

demo采用Asp.net Core MVC作為示例

 

項目中引入我們所需要的幾個程序集。即紅框中的程序集。

配置我們的數據庫連接:

在appsettings.json中進行配置,如下:

{
  "DataBaseSetting": {
    "ConnectionString": "mongodb://127.0.0.1",
    "DatabaseName": "DPMS"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
DataBaseSetting名字必須是固定的,因為我們底層連接默認就是這個名字。

 接下來就是做數據庫連接的映射和注入,以及數據庫上下文的注入
在Startup.cs 文件中,如下:

        public void ConfigureServices(IServiceCollection services)
        {
            
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //讀取appsettings.json文件中的MongoDbSettings節點數據,賦值給MongoDbSettings對象
            services.Configure<DataBaseSetting>(
                Configuration.GetSection(nameof(DataBaseSetting)));

            //注入MongoDbSettings對象
            services.AddSingleton<IDataBaseSetting>(sp =>
                sp.GetRequiredService<IOptions<DataBaseSetting>>().Value);

            ////注入上下文對象
            services.AddScoped<DbContextBase>();
            //注冊程序集
            services.AddKySharpService(new string[]{ "DPMS.Repository", "DPMS.Service" });

        }

 

 按照如上,完成我們的注入工作。其中 數據庫配置和數據庫上下文都是必須注入的。
程序集在底層實現了批量注入的邏輯,程序集的注入必須按照先后順序進行。

 

下面在Web中使用,創建控制器Home,並完成在構造函數中實例化 return model.ID.ToString();

 

        /// <summary>
        /// 定義接口類型對象
        /// </summary>
        private readonly IInvestService _investService;
        public HomeController(IInvestService investService)
        {
            //完成構造函數中的實例化
            this._investService = investService;
        }
        public string Index()
        {
            var model = new Invest {CD_No = "aasd"};
            _investService.AddInvest(model);//調用服務層進行寫入
            return model.ID.ToString();
        }

 

如上代碼,實現了 實現類與接口的控制反轉。

如果我們不用服務層,如何直接使用倉儲層,原理是一樣的,見下面代碼

 /// <summary>
        /// 定義接口類型對象
        /// </summary>
        private readonly IInvestService _investService;

        private readonly IInvestRepository _investRepository;
        public HomeController(IInvestService investService, IInvestRepository investRepository)
        {
            //完成構造函數中的實例化
            this._investService = investService;
            _investRepository = investRepository;
        }
        public string Index()
        {
            var model = new Invest {CD_No = "aasd"};
            _investRepository.Add(model);//調用服務層進行寫入
            return model.ID.ToString();
        }

異步的方法:

 public async Task<string> Index2()
        {
            var model = new Invest { CD_No = "aasd" };
           await _investRepository.AddAsync(model);//調用服務層進行寫入
            return model.ID.ToString();
        }

在KYSharpCore.MongoDB中,已經完全實現了異步的操作方法。

 

項目源碼:

鏈接:https://pan.baidu.com/s/1X9ZM4zWaMWSkN61v8uay_Q
提取碼:1hys


免責聲明!

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



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