-3

Using MongoDB C# driver 2.4.2, try to establish some reference but getting the err for the last line regarding _db.

"A field initializer cannot reference the non-static field, method or property CurrentClassName._client"

Can't figure it out.

Code:

public class MongoDatabase<T> : ImyDB<T> where T : class, new()
{
private static string _connectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
private string _dbName;
private MongoClient _client = new MongoClient(_connectionString);
private IMongoDatabase _db = _client.GetDatabase(_dbName);
Jeb50
  • 6,272
  • 6
  • 49
  • 87

1 Answers1

1

You are referencing _client field in the initializer of _db field. From C# specification 10.4.5.2 Instance field initialization

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

You can move both initializations to constructor, or at least you should move _db initialization there:

public MongoDatabase()
{
   _client = new MongoClient(_connectionString);
   _db = _client.GetDatabase(_dbName);
}

I would also consider injection client into your class, and moving config-reading responsibility to your IoC containter configuration.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459