Repository Pattern with MongoDB .NET Driver and .NET Core WebAPI

Dharmik Valani
Mongo Db with .NetCore
3 min readMay 15, 2020

Hello ,

In this Post I will show you that how to implement a Repository Pattern in .Net core Web API when using a MongoDB database.

I will use the following tools for the development:

  1. Visual Studio 2019 Community Edition (free)
  2. MongoDb Database

What is a Repository?

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.

Creating a Web API Project

  1. Open Visual Studio and select Create a new project -> ASP.NET Core Web Application. Then, name the solution and the project.

2. Select a API and Create a Project

1. Creating a Connection Between MongoDb and .Net CoreAPI

Open AppSetting.json and add a connection String for mongo db

Here i am using my cluster Connection string , You can use your local Mongo connections

2. Create a ConnectionSetting class Where we can use this ConnectionString and Database

3. Add this Class Service inside Startup.cs > ConfigureService

4.Now Create a Interface IUserContext where we can declare Our All MongoDb Collections or Tables

5.Now Create a UserContext class where we can initialize mongodb connection and our database and access our collection or tables

6. Now add this to configure services So it will initialize when Project build


services.AddTransient<IUserContext, UserContext>();

7. Now Create a Interface for our repository class to add some Method declarations

8. Now we create a Repository For our class and use Dependency Injection Through Constructor and also Implement interface to our repository class.

Here , We initialize Our Data context class to access data from mongodb or Implement a CRUD Operation

9. Now Create a Controller, and from controler we use repository methods.

For Full Code Uploaded in my github Account :

This is a Basic Repository Understand . For Full Code On GitHub .

Please like and Comment in my Blog

Thank You ,

References

  1. https://www.matheus.ro/2018/03/05/getting-started-mongodb-using-asp-net-core-2-web-api/
  2. https://qappdesign.com/code/using-mongodb-with-net-core-webapi/
{public class ConnectionSetting{public string ConnectionString { get; set; }public string Database { get; set; }}}

--

--