1.我们再ABP项目添加一个.NET Core类库 类库名自定定义, 我这里定义为 TexHong_EMWX.MongoDb
添加NuGet包。
ABP
mongocsharpdriver
添加 AbpMongoDbConfigurationExtensions.cs
////// 定义扩展方法 允许配置ABP MongoDB模块 /// public static class AbpMongoDbConfigurationExtensions { /// /// 用于配置ABP MongoDB模块。 /// public static IAbpMongoDbModuleConfiguration AbpMongoDb(this IModuleConfigurations configurations) { return configurations.AbpConfiguration.Get (); } }
添加 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
////// Implements IRepository for MongoDB. /// /// Type of the Entity for this repository public class MongoDbRepositoryBase : MongoDbRepositoryBase int>, IRepository where TEntity : class, IEntity<int> { public MongoDbRepositoryBase(IMongoDatabaseProvider databaseProvider) : base(databaseProvider) { } } /// /// Implements IRepository for MongoDB. /// /// Type of the Entity for this repository /// Primary key of the entity public class MongoDbRepositoryBase : AbpRepositoryBase where TEntity : class, IEntity { public virtual MongoDatabase Database { get { return _databaseProvider.Database; } } public virtual MongoCollection Collection { get { return _databaseProvider.Database.GetCollection (typeof(TEntity).Name); } } private readonly IMongoDatabaseProvider _databaseProvider; public MongoDbRepositoryBase(IMongoDatabaseProvider databaseProvider) { _databaseProvider = databaseProvider; } public override IQueryable GetAll() { return Collection.AsQueryable(); } public override TEntity Get(TPrimaryKey id) { var query = MongoDB.Driver.Builders.Query .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 .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 .EQ(e => e.Id, id); Collection.Remove(query); } }
添加 MongoDbUnitOfWork.cs
////// Implements Unit of work for MongoDB. /// public class MongoDbUnitOfWork : UnitOfWorkBase, ITransientDependency { /// /// Gets a reference to MongoDB Database. /// public MongoDatabase Database { get; private set; } private readonly IAbpMongoDbModuleConfiguration _configuration; /// /// Constructor. /// 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
////// Implements that gets database from active unit of work. /// 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 { ////// Gets the . /// MongoDatabase Database { get; } }
添加 TexHong_EMWXMongoDBModule.cs
////// This module is used to implement "Data Access Layer" in MongoDB. /// [DependsOn(typeof(AbpKernelModule))] public class TexHong_EMWXMongoDBModule : AbpModule { public override void PreInitialize() { IocManager.Register (); // 配置 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 long>>(); } }
最后项目的架构
添加单元测试 MongoDbAppService_Tests.cs
public class MongoDbAppService : TexHong_EMWXTestBase { private readonly MongoDbRepositoryBaselong> _mongoDbUserRepositoryBase; public MongoDbAppService() { this._mongoDbUserRepositoryBase = Resolve 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添加进去,不然会导致运行失败无法注入。
源码下载:https://download.csdn.net/download/liaoyide/11742718