ABP 結合 MongoDB 集成依賴註入

来源:https://www.cnblogs.com/liaoyd/archive/2019/09/14/11514672.html
-Advertisement-
Play Games

1.我們再ABP項目添加一個.NET Core類庫 類庫名自定定義, 我這裡定義為 TexHong_EMWX.MongoDb 添加NuGet包。 ABP mongocsharpdriver 添加 AbpMongoDbConfigurationExtensions.cs 添加 AbpMongoDbMo ...


1.我們再ABP項目添加一個.NET Core類庫  類庫名自定定義, 我這裡定義為 TexHong_EMWX.MongoDb

添加NuGet包。

ABP

mongocsharpdriver

 

 

添加 AbpMongoDbConfigurationExtensions.cs

 /// <summary>
    /// 定義擴展方法 <see cref="IModuleConfigurations"/> 允許配置ABP MongoDB模塊
    /// </summary>
    public static class AbpMongoDbConfigurationExtensions
    {
        /// <summary>
        /// 用於配置ABP MongoDB模塊。
        /// </summary>
        public static IAbpMongoDbModuleConfiguration AbpMongoDb(this IModuleConfigurations configurations)
        {
            return configurations.AbpConfiguration.Get<IAbpMongoDbModuleConfiguration>();
        }
    }

添加 AbpMongoDbModuleConfiguration.cs

 internal class AbpMongoDbModuleConfiguration : IAbpMongoDbModuleConfiguration
    {
        public string ConnectionString { get; set; }

        public string DatabaseName { get; set; }
    }

添加  IAbpMongoDbModuleConfiguration

  public interface IAbpMongoDbModuleConfiguration
    {
        string ConnectionString { get; set; }

        string DatabaseName { get; set; }
    }

 

添加 MongoDbRepositoryBase.cs

/// <summary>
    /// Implements IRepository for MongoDB.
    /// </summary>
    /// <typeparam name="TEntity">Type of the Entity for this repository</typeparam>
    public class MongoDbRepositoryBase<TEntity> : MongoDbRepositoryBase<TEntity, int>, IRepository<TEntity>
        where TEntity : class, IEntity<int>
    {
        public MongoDbRepositoryBase(IMongoDatabaseProvider databaseProvider)
            : base(databaseProvider)
        {
        }
    }
    /// <summary>
    /// Implements IRepository for MongoDB.
    /// </summary>
    /// <typeparam name="TEntity">Type of the Entity for this repository</typeparam>
    /// <typeparam name="TPrimaryKey">Primary key of the entity</typeparam>
    public class MongoDbRepositoryBase<TEntity, TPrimaryKey> : AbpRepositoryBase<TEntity, TPrimaryKey>
        where TEntity : class, IEntity<TPrimaryKey>
    {
        public virtual MongoDatabase Database
        {
            get { return _databaseProvider.Database; }
        }
        public virtual MongoCollection<TEntity> Collection
        {
            get
            {
                return _databaseProvider.Database.GetCollection<TEntity>(typeof(TEntity).Name);
            }
        }
        private readonly IMongoDatabaseProvider _databaseProvider;
        public MongoDbRepositoryBase(IMongoDatabaseProvider databaseProvider)
        {
            _databaseProvider = databaseProvider;
        }

        public override IQueryable<TEntity> GetAll()
        {
            return Collection.AsQueryable();
        }

        public override TEntity Get(TPrimaryKey id)
        {
            var query = MongoDB.Driver.Builders.Query<TEntity>.EQ(e => e.Id, id);
            var entity = Collection.FindOne(query);
            if (entity == null)
            {
                throw new EntityNotFoundException("There is no such an entity with given primary key. Entity type: " + typeof(TEntity).FullName + ", primary key: " + id);
            }
            return entity;
        }
        public override TEntity FirstOrDefault(TPrimaryKey id)
        {
            var query = MongoDB.Driver.Builders.Query<TEntity>.EQ(e => e.Id, id);
            return Collection.FindOne(query);
        }
        public override TEntity Insert(TEntity entity)
        {
            Collection.Insert(entity);
            return entity;
        }
        public override TEntity Update(TEntity entity)
        {
            Collection.Save(entity);
            return entity;
        }
        public override void Delete(TEntity entity)
        {
            Delete(entity.Id);
        }
        public override void Delete(TPrimaryKey id)
        {
            var query = MongoDB.Driver.Builders.Query<TEntity>.EQ(e => e.Id, id);
            Collection.Remove(query);
        }
    }

添加 MongoDbUnitOfWork.cs 

/// <summary>
    /// Implements Unit of work for MongoDB.
    /// </summary>
    public class MongoDbUnitOfWork : UnitOfWorkBase, ITransientDependency
    {
        /// <summary>
        /// Gets a reference to MongoDB Database.
        /// </summary>
        public MongoDatabase Database { get; private set; }

        private readonly IAbpMongoDbModuleConfiguration _configuration;

        /// <summary>
        /// Constructor.
        /// </summary>
        public MongoDbUnitOfWork(
            IAbpMongoDbModuleConfiguration configuration,
            IConnectionStringResolver connectionStringResolver,
            IUnitOfWorkFilterExecuter filterExecuter,
            IUnitOfWorkDefaultOptions defaultOptions)
            : base(
                  connectionStringResolver,
                  defaultOptions,
                  filterExecuter)
        {
            _configuration = configuration;
            BeginUow();
        }

#pragma warning disable
        protected override void BeginUow()
        {
            //TODO: MongoClientExtensions.GetServer(MongoClient)' is obsolete: 'Use the new API instead.
            Database = new MongoClient(_configuration.ConnectionString)
                .GetServer()
                .GetDatabase(_configuration.DatabaseName);
        }
#pragma warning restore

        public override void SaveChanges()
        {

        }

#pragma warning disable 1998
        public override async Task SaveChangesAsync()
        {

        }
#pragma warning restore 1998

        protected override void CompleteUow()
        {

        }

#pragma warning disable 1998
        protected override async Task CompleteUowAsync()
        {

        }
#pragma warning restore 1998
        protected override void DisposeUow()
        {

        }
    }

添加  UnitOfWorkMongoDatabaseProvider.cs

/// <summary>
    /// Implements <see cref="IMongoDatabaseProvider"/> that gets database from active unit of work.
    /// </summary>
    public class UnitOfWorkMongoDatabaseProvider : IMongoDatabaseProvider, ITransientDependency
    {
        public MongoDatabase Database { get { return _mongoDbUnitOfWork.Database; } }

        private readonly MongoDbUnitOfWork _mongoDbUnitOfWork;

        public UnitOfWorkMongoDatabaseProvider(MongoDbUnitOfWork mongoDbUnitOfWork)
        {
            _mongoDbUnitOfWork = mongoDbUnitOfWork;
        }
    }

添加 IMongoDatabaseProvider.cs

public interface IMongoDatabaseProvider
    {
        /// <summary>
        /// Gets the <see cref="MongoDatabase"/>.
        /// </summary>
        MongoDatabase Database { get; }
    }

添加 TexHong_EMWXMongoDBModule.cs

  

/// <summary>
    /// This module is used to implement "Data Access Layer" in MongoDB.
    /// </summary>
    [DependsOn(typeof(AbpKernelModule))]
    public class TexHong_EMWXMongoDBModule : AbpModule
    {
        public override void PreInitialize()
        {
            IocManager.Register<IAbpMongoDbModuleConfiguration, AbpMongoDbModuleConfiguration>();            
            // 配置 MonggoDb 資料庫地址與名稱
            IAbpMongoDbModuleConfiguration abpMongoDbModuleConfiguration = Configuration.Modules.AbpMongoDb();
            abpMongoDbModuleConfiguration.ConnectionString = "mongodb://admin:[email protected]:27017/texhong_em";
            abpMongoDbModuleConfiguration.DatabaseName = "texhong_em";
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(TexHong_EMWXMongoDBModule).GetAssembly());            
            IocManager.Register<MongoDbRepositoryBase<User, long>>();
        }
    }

最後項目的架構

 

 

 

添加單元測試  MongoDbAppService_Tests.cs 

 public class MongoDbAppService : TexHong_EMWXTestBase
    {
        private readonly MongoDbRepositoryBase<User,long> _mongoDbUserRepositoryBase;
        
        public MongoDbAppService()
        {
           this._mongoDbUserRepositoryBase = Resolve<MongoDbRepositoryBase<User, long>>();
        }
        [Fact]
        public async Task CreateUsers_Test()
        {
            long Id = (DateTime.Now.Ticks - 621356256000000000) / 10000;            
            await _mongoDbUserRepositoryBase.InsertAndGetIdAsync(new User() { Id= Id, Name = "123", EmailConfirmationCode = "1111", UserName = "2222" });
            User user = _mongoDbUserRepositoryBase.Get(Id);
        }        
    }

註意單元測試要引用 MongoDb項目。

同時在TestModule.cs屬性依賴 DependsOn 把Mongodb 的 Module添加進去,不然會導致運行失敗無法註入。

 


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

-Advertisement-
Play Games
更多相關文章
  • 簡介 簡單來說,springcloud的就是由一組springboot應用(服務)組成,相互之間通過REST等方式進行通信。 兩個springboot應用,其中一個作為服務提供者,一個作為服務消費者,我認為這就構成了一個最簡單的springcloud應用,之後其他的工具都是為這兩個應用來服務的。 我 ...
  • 源代碼:# dict1 是 字典 , 用來對應相應元素的下標,我們將文件轉成列表,對應的也就是文件的下標,通過下標來找文件元素dict1 = {'sort':0 , 'name':1 ,'age':2 ,'phone':3 ,'job':4 }#將最後需要列印的信息轉成列表的形式def p_mess ...
  • 今日所學: /* 2019.08.19開始學習,此為補檔。 */ 1.this: ①this是成員方法的一個特殊的固有的本地變數,它表達了調用這個方法的那個對象。 ②在成員方法內部直接調用自己(this)的其他方法。 2.本地(局部)變數: ①定義在方法內部的變數是本地變數。 ②本地變數的生存期和作 ...
  • 一、前言 一直想寫一篇Dpper的定製化擴展的文章,但是裡面會設計到對Lambda表達式的解析,而解析Lambda表達式,就必須要知道表達式樹的相關知識點。我希望能通過對各個模塊的知識點或者運用能夠多一點的講解,能夠幫助到園友瞭解得更多。雖然講解得不全面,如果能成為打開這塊的一把鑰匙,也是蝸牛比較欣 ...
  • 一、前言 剛開始工作的時候,覺得委托和事件有些神秘,而當你理解他們之後,也覺得好像沒有想象中的那麼難。在項目中運用委托和事件,你會發現他非常棒,這篇博文算是自己對委托和事件的一次梳理和總結。 二、委托 C#中的委托,相當於C++中的指針函數,但委托是面向對象的,是安全的,是一個特殊的類,當然他也是引 ...
  • 前言: 現在越來越多的項目或多或少會用到JWT,為什麼會出現使用JWT這樣的場景的呢? 假設現在有一個APP,後臺是分散式系統。APP的首頁模塊部署在上海機房的伺服器上,子頁面模塊部署在深圳機房的伺服器上。此時你從首頁登錄了該APP,然後跳轉到子頁面模塊。session在兩個機房之間不能同步,用戶是 ...
  • 前段時間公司又一輪安全審查,要求對各項目進行安全掃描,排查漏洞並修複,手上有幾個歷史項目,要求在限定的時間內全部修複並提交安全報告,也不清楚之前是如何做的漏洞修複,這次使用工具掃描出來平均每個項目都還有大概100來個漏洞。這些漏洞包括SQL語句註入,C#後端代碼,XML文件,以及前端HTML,JS代 ...
  • 部署asp.net網站到Azure 前言 前些天一直在寫一個單頁面web應用程式,終於完成了,於是考慮發佈到雲伺服器。本人沒有AWS賬號,遂本打算使用谷歌雲。參考文檔後發現官方文檔給出的方式為在visual studio上使用Cloud Tools for Visual Studio插件,然而該插件 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...