MongoHelper.cs

using System;
using MongoDB.Bson;
using MongoDB;
using System.Web;
using MongoDB.Driver;

namespace YSF.ImageUtility
{
//
//http://blog.csdn.net/dannywj1371/article/details/7440916
//https://github.com/mongodb/mongo-csharp-driver
//http://docs.mongodb.org/ecosystem/drivers/csharp-community-projects/
public class MongoDBHelper
{
private const string CurrentSessionKey = "mongodb.current_session";

private static string dbName = "test";
static string connectionString = "mongodb://localhost";
static MongoClient client = null;
static MongoServer server = null;
//static MongoDatabase database = null;// WriteConcern defaulted to Acknowledged

static MongoDBHelper()
{
client = new MongoClient(connectionString);
}

/// <summary>
/// 打开一个数据库连接
/// </summary>
public static MongoDatabase Open()
{
if (HttpContext.Current != null)
{
server = HttpContext.Current.Session[CurrentSessionKey] as MongoServer;

if (server == null)
{
server = client.GetServer();
HttpContext.Current.Session[CurrentSessionKey] = server;
}
}
else
{
server = client.GetServer();
}
server.Connect();

return server.GetDatabase(dbName);
}

/// <summary>
/// 不要忘记关闭连接
/// </summary>
public static void Close()
{
if (HttpContext.Current == null)
{
return;
}

if (server == null)
{
server = HttpContext.Current.Session[CurrentSessionKey] as MongoServer;
}

if (server != null)
{
server.Disconnect();
}
}
}

//public class MongoDBHelper
//{
// private const string CurrentSessionKey = "mongodb.current_session";

// //string strCon = @"mongodb://admin:xPlBBU7H1cDr@127.6.127.130:27017/";
// private static string strConnection = @"mongodb://localhost/";
// private static string dbName = "bolo";
// private static MongoConfigurationBuilder config = new MongoConfigurationBuilder();

// static MongoDBHelper()
// {
// // COMMENT OUT FROM HERE
// config.Mapping(mapping =>
// {
// mapping.Map<Account>();
// mapping.Map<Live>();

// });
// config.ConnectionString(strConnection);
// }

// /// <summary>
// /// 打开一个数据库连接
// /// </summary>
// public static IMongoDatabase Open()
// {
// Mongo mongo = null;
// if (HttpContext.Current != null)
// {
// mongo = HttpContext.Current.Session[CurrentSessionKey] as Mongo;

// if (mongo == null)
// {
// mongo = new Mongo(config.BuildConfiguration());
// HttpContext.Current.Session[CurrentSessionKey] = mongo;
// }
// mongo.Connect();
// }
// else
// {
// mongo = new Mongo(config.BuildConfiguration());
// mongo.Connect();
// }

// return mongo.GetDatabase(dbName);
// }

// /// <summary>
// /// 不要忘记关闭连接
// /// </summary>
// public static void Close()
// {
// if (HttpContext.Current == null)
// {
// return;
// }

// var mongo = HttpContext.Current.Session[CurrentSessionKey] as Mongo;
// if (mongo != null)
// {
// mongo.Disconnect();
// }
// }
//}
}

 

  

posted @ 2015-05-08 18:49  FrankHu  阅读(293)  评论(0编辑  收藏  举报