ABP 结合 MongoDB 集成依赖注入
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:123qwe@118.126.93.113: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添加进去,不然会导致运行失败无法注入。
源码下载:https://download.csdn.net/download/liaoyide/11742718