简体   繁体   中英

Can't .net project mongodb connection .Whats wrong

My context Class

 public class Context
    {
        private readonly IMongoDatabase _database;
        public Context(IOptions<Settings> settings)
        {
            var client = new MongoClient(settings.Value.ConnectionString);
            _database = client.GetDatabase(settings.Value.Database);

        }
        public IMongoCollection<TEntity> GetCollection<TEntity>()
        {
            return _database.GetCollection<TEntity>(typeof(TEntity).Name.Trim());
        }
        public IMongoDatabase GetDatabase()
        {
            return _database;
        }
    }

My AppsettingJson

"MongoConnection": {
    "ConnectionString": "mongodb+srv://username:mypassword@mongodb.net/ODSDataBase?retryWrites=true&w=majority",
    "Database": "ODSDataBase"

My Settings class

public class Settings
    {
        public string ConnectionString;

        public string Database;
    }

My Repository injection

private readonly Context.Context _context;
private readonly IMongoCollection _collection;

public MongoRepositoryBase(IOptions<Settings> settings)
        
{
     _context = new Context.Context(settings);            
     _collection=_context.GetCollection<TEntity>();
}

you can use this github to check your code

https://github.com/MohammadAsadi1372/TestMongoDB/tree/master/TestMongoDB

and this link is use mongo in docker

https://github.com/MohammadAsadi1372/TestMongoDB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM