前几天在网上想找一下Asp.Net Core使用MongoDB相关的文章,也看了几篇,发现都是在写简单的例子,这样的例子是不能用在生产环境的,不能用的生产环境的。封装一个东西一定是建立在你对这个东西足够了解的前提下完成,最起码官方的文档你要看吧。

1、MongoClient 和 MongoDatabase 这两个对象的生命周期怎么处理?
2、每次插入一个document都要动态获取一个Collection吗?

先看一下官方给出的这篇文章:
https://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/connecting/

看完这篇文档我们发现MongoClient、MongoDatabase和MongoCollection都是可以重用的,而且是线程安全的。核心代码:

public class MongoRepository<T> where T : class, new()
{
    // https://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/connecting/#re-use
    private readonly MongoOptions _options;
    private static IMongoClient _mongoClient;
    private static IMongoDatabase _mongoDatabase;
    private static object _obj = new object();

    private static readonly ConcurrentDictionary<RuntimeTypeHandle, IMongoCollection<T>> _mongoCollections = new ConcurrentDictionary<RuntimeTypeHandle, IMongoCollection<T>>();
    public MongoRepository(IOptions<MongoOptions> optionsAccessor)
    {
        if (optionsAccessor == null)
        {
            throw new ArgumentNullException(nameof(optionsAccessor));
        }
        _options = optionsAccessor.Value;

        if (_mongoClient == null)
        {
            lock (_obj)
            {
                if (_mongoClient == null)
                {
                    _mongoClient = new MongoClient(_options.ConnectionString);
                    _mongoDatabase = _mongoClient.GetDatabase(_options.DataBaseName);
                }
            }
        }
    }

    public void Insert(T document)
    {
        this.GetCollection(document).InsertOne(document);
    }

    private IMongoCollection<T> GetCollection(T document)
    {
        if (_mongoCollections.TryGetValue(document.GetType().TypeHandle, out IMongoCollection<T> collection))
        {
            return collection;
        }

        collection = _mongoDatabase.GetCollection<T>(typeof(T).Name);
        _mongoCollections.TryAdd(document.GetType().TypeHandle, collection);

        return collection;
    }
}
public class MongoOptions
{
    public string ConnectionString { get; set; }
    public string DataBaseName { get; set; }
}
public static class MongoServiceCollectionExtensions
{
    public static IServiceCollection AddMongo(this IServiceCollection services, Action<MongoOptions> setupAction)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }

        if (setupAction == null)
        {
            throw new ArgumentNullException(nameof(setupAction));
        }

        services.AddOptions();
        services.Configure(setupAction);
        services.AddScoped(typeof(MongoRepository<>));

        return services;
    }
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddMongo(options =>
    {
        options.ConnectionString = "mongodb://localhost:27017";
        options.DataBaseName = "oneaspnet";
    });
}

Asp.Net Core Use MongoDB的更多相关文章

  1. asp.net core集成MongoDB

    0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.前言及MongoDB的介绍 最近在整合自己的框架,顺便把MongoDBD的最简单CRUD重构一下作为组件化集成到asp.net ...

  2. ASP.NET Core使用MongoDB数据库

    环境:Asp.Net Core Mvc 2.2,MongoDB 4.09 参考文档:http://mongodb.github.io/mongo-csharp-driver/ http://mongo ...

  3. Asp.Net Core使用MongoDB

    MongoDB 是一个基于分布式且面向文档存储的开源 NoSql数据库系统 MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.它支持的数据结构 ...

  4. ASP.NET Core 实战:使用 NLog 将日志信息记录到 MongoDB

    一.前言 在项目开发中,日志系统是系统的一个重要组成模块,通过在程序中记录运行日志.错误日志,可以让我们对于系统的运行情况做到很好的掌控.同时,收集日志不仅仅可以用于诊断排查错误,由于日志同样也是大量 ...

  5. Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程

    Asp.Net Core Web Api图片上传及MongoDB存储实例教程(一) 图片或者文件上传相信大家在开发中应该都会用到吧,有的时候还要对图片生成缩略图.那么如何在Asp.Net Core W ...

  6. Using MongoDB with Web API and ASP.NET Core

    MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which a ...

  7. 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null

    问题描述: POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null ...

  8. ASP.NET Core+MongoDB(一)

    项目类库:.Net Standar 2.0web:ASP.NET CORE 2.2 版本 先上图,看我们的解决方案结构: 分别对上面的工程进行说明:1.KYSharpCore:为公共的基础类,最底层 ...

  9. ASP.NET Core 之 Identity 入门(三)

    前言 在上一篇文章中,我们学习了 CookieAuthentication 中间件,本篇的话主要看一下 Identity 本身. 最早2005年 ASP.NET 2.0 的时候开始, Web 应用程序 ...

随机推荐

  1. Who's in the Middle

    FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' ...

  2. JDK8.0新特性

    连接转载地址:http://www.2cto.com/kf/201609/544044.html Eclipse: http://aiyiupload.oss-cn-beijing.aliyuncs. ...

  3. 一、源代码-面向CLR的编译器-托管模块-(元数据&IL代码)

    本文脉络图如下: 1.CLR(Common Language Runtime)公共语言运行时简介 (1).公共语言运行时是一种可由多种编程语言一起使用的"运行时". (2).CLR ...

  4. JavaScript的DOM编程--06--两个实验

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  5. 物联网细分领域-车联网(OBD)市场分析

    前言: 这段时间在跟一个车联网的项目,所以做了一些研究. OBD概述 OBD是英文On-Board Diagnostic的缩写,中文翻译为"车载诊断系统".这个系统随时监控发动机的 ...

  6. Augustus安装小记

    之前安装过一次Augustus,由于节点重新部署后,原来安装的硬盘被格掉了,今天重新安装的时候出了一些问题,记录一下. 1. 需要boost,安装好boost之后,虽然将其加入到~/.bashrc配置 ...

  7. Android Studio移动鼠标显示悬浮提示的设置方法

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  8. Debian安装fail2ban来防止扫描

    vps的root密码不要设置的太简单,这样很容易被攻破,你可以安装如下软件来降低vps被攻破的机会. 输入如下命令: apt-get install fail2ban 提示如下表示安装完成: root ...

  9. QuickStart系列:docker部署之Elasticsearch

    ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是用Java开发的,并作为Apach ...

  10. JAVA中的按值传递

    Java中只有按值传递,没有按引用传递! 方法参数共有两种类型: 基本数据类型 对象引用 一:基本数据类型 首先看一个小例子: package chuandi; public class Test1 ...