Skip to content

Instantly share code, notes, and snippets.

@helderboone
Last active January 6, 2022 21:41
Show Gist options
  • Save helderboone/0e228a9c39c60813882f6c204bf6f71a to your computer and use it in GitHub Desktop.
Save helderboone/0e228a9c39c60813882f6c204bf6f71a to your computer and use it in GitHub Desktop.
MongoDb settings for asp.net core
{
"MongoConnection": {
"ConnectionString": "mongodb://helder:123@localhost:27017/test",
"Database": "test"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
public class NoteContext
{
private readonly IMongoDatabase _database = null;
public NoteContext(IOptions<Settings> settings)
{
var client = new MongoClient(settings.Value.ConnectionString);
if (client != null)
_database = client.GetDatabase(settings.Value.Database);
}
public IMongoCollection<Note> Notes
{
get
{
return _database.GetCollection<Note>("Note");
}
}
public class Settings
{
public string ConnectionString;
public string Database;
}
public class NoteRepository : INoteRepository
{
private readonly NoteContext context = null;
public NoteRepository(IOptions<Settings> settings)
{
context = new NoteContext(settings);
}
public async Task<IEnumerable<Note>> GetAllNotes()
{
return await context.Notes.Find(_ => true).ToListAsync();
}
public async Task<Note> GetNote(string id)
{
var filter = Builders<Note>.Filter.Eq("Id", id);
return await context.Notes
.Find(filter)
.FirstOrDefaultAsync();
}
public void AddNote(Note item)
{
context.Notes.InsertOne(item);
}
}
public interface INoteRepository
{
Task<IEnumerable<Note>> GetAllNotes();
Task<Note> GetNote(string id);
void AddNote(Note item);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<Settings>(options =>
{
options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
options.Database = Configuration.GetSection("MongoConnection:Database").Value;
});
services.AddTransient<INoteRepository, NoteRepository>();
}
@anthonydass78
Copy link

great !!! thanks for posting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment