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 - ) / ;
await _mongoDbUserRepositoryBase.InsertAndGetIdAsync(new User() { Id= Id, Name = "", EmailConfirmationCode = "", UserName = "" });
User user = _mongoDbUserRepositoryBase.Get(Id);
}
}
注意单元测试要引用 MongoDb项目。
同时在TestModule.cs属性依赖 DependsOn 把Mongodb 的 Module添加进去,不然会导致运行失败无法注入。

源码下载:https://download.csdn.net/download/liaoyide/11742718
ABP 结合 MongoDB 集成依赖注入的更多相关文章
- 基于ABP模块组件与依赖注入组件的项目插件开发
注意,阅读本文,需要先阅读以下两篇文章,并且对依赖注入有一定的基础. 模块系统:http://www.cnblogs.com/mienreal/p/4537522.html 依赖注入:http://w ...
- Asp.Net Core 3.1 Api 集成Abp项目依赖注入
Abp 框架 地址https://aspnetboilerplate.com/ 我们下面来看如何在自己的项目中集成abp的功能 我们新建core 3.1 API项目和一个core类库 然后 两个项目都 ...
- ABP+AdminLTE+Bootstrap Table权限管理系统第四节--仓储,服务,服务接口及依赖注入
在ABP框架中,仓储,服务,这块算是最为重要一块之一了.ABP框架提供了创建和组装模块的基础,一个模块能够依赖于另一个模块,一个程序集可看成一个模块, 一个模块可以通过一个类来定义这个模块,而给定义这 ...
- ABP中的依赖注入思想
在充分理解整个ABP系统架构之前首先必须充分了解ABP中最重要的依赖注入思想,在后面会具体举出一些实例来帮助你充分了解ABP中的依赖注入思想,在了解这个之前我们首先来看看什么是依赖注入?来看看维基百科 ...
- 基于DDD的.NET开发框架 - ABP日志Logger集成
返回ABP系列 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应 ...
- ABP(现代ASP.NET样板开发框架)系列之6、ABP依赖注入
点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之6.ABP依赖注入 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)” ...
- ABP框架 - 依赖注入
文档目录 本节内容: 什么是依赖注入 传统方式的问题 解决方案 构造器注入模式 属性注入模式 依赖注入框架 ABP 依赖注入基础 注册依赖 约定注入 辅助接口 自定义/直接 注册 使用IocManag ...
- ABP理论学习之依赖注入
返回总目录 本篇目录 什么是依赖注入 传统方式产生的问题 解决办法 依赖注入框架 ABP中的依赖注入基础设施 注册 解析 其他 ASP.NET MVC和ASP.NET Web API集成 最后提示 什 ...
- 基于DDD的.NET开发框架 - ABP依赖注入
返回ABP系列 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应 ...
随机推荐
- @RequestBody的使用
一.说明 首先@RequestBody需要接的参数是一个string化的json,这里直接使用JSON.stringify(json)这个方法来转化 其次@RequestBody,从名称上来看也就是说 ...
- Spring Cloud Feign 调用过程分析
前面已经学习了两个Spring Cloud 组件: Eureka:实现服务注册功能: Ribbon:提供基于RestTemplate的HTTP客户端并且支持服务负载均衡功能. 通过这两个组件我们暂时可 ...
- 【MySQL】Mysql模糊查询like提速优化
一般情况下like模糊查询的写法为(field已建立索引): SELECT `column` FROM `table` WHERE `field` like '%keyword%'; 上面的语句用ex ...
- Web容器中DefaultServlet详解 JspServlet DefaultServlet
Web容器中DefaultServlet详解 https://blog.csdn.net/qq_30920821/article/details/78328608 Web容器中DefaultServl ...
- C# .net 高清压缩图片 合并图片方法
/// <summary> /// 合并宽度一样的图片 /// </summary> /// <param name="imgUrls">多张图 ...
- windows cmd ftp 自动下载
1.编写ftp的bat脚本: set year=%,% set day=%,%%,%%,% mkdir d:\ftp\%,% mkdir d:\ftp\%,%\%,%%,%%,% del d:\ftp ...
- LeetCode 104. Maximum Depth of Binary Tree(二叉树深度)
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the long ...
- DownloadURLFile网络文件下载
import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; impo ...
- blade-boot操作之Idea使用Mave和Dockerfile文件推送到harbor仓库
mvn clean package docker:build 错误提示: Failed to execute goal com.spotify:docker-maven-plugin:1.1.0:bu ...
- Pi1-lite
第一次加电无显示器怎么办?无解. 网上说在tf卡的根下建立ssh空文件来启动ssh服务,建立wpa_supplicant.conf文件来连接wifi. 我怎么都试不出来,只能老老实实接显示器.键盘.网 ...