Jim
Jim

Reputation: 4950

How to use configuration for MongoDb (MongClient) connections?

I would like to use the configuration file (App.Config) to specify MongoClient connection string. Is there a built in way to do this or can I just use the ConnectionStringsSection?

Upvotes: 1

Views: 4712

Answers (1)

nercan
nercan

Reputation: 207

Config

    <connectionStrings>
    <add name="MongoSessionServices" connectionString="mongodb:/localhost:27017" />
    <add name="DefaultMongoConnection" connectionString="mongodb://localhost:27017" />
  </connectionStrings>
  <appSettings>

    <add key="MongoDbName" value="your_database" />

  </appSettings>

Get Mongo Server

 public static MongoServer GetConnection()
        {

            MongoClient mc = new MongoClient(string.IsNullOrEmpty(ConnectionText) ? System.Configuration.ConfigurationManager.ConnectionStrings["DefaultMongoConnection"].ConnectionString : ConnectionText);
            return mc.GetServer();
        }

Get Mongo Database

 public static MongoDatabase GetDatabase(string database = "")
        {
            if (string.IsNullOrEmpty(database))
            {
                return GetConnection().GetDatabase(string.IsNullOrEmpty(DatabaseText) ? System.Configuration.ConfigurationManager.AppSettings.Get("MongoDbName") : DatabaseText);
            }
            else
            {
                return GetConnection().GetDatabase(database);
            }
        }

Upvotes: 5

Related Questions