Search code examples
c#mongodbsingletonrepositorydata-access-layer

Patterns for Mongodb c# client


I want to use mongodb for a project.

OK yes, i able to connect to it and do things.

However, I want to be able to wrap the mongodb driver around a wrapper so if i want to change the database, i want to be easily change it.

Repository pattern looks like something I can use with Mongodb, but I m kinda over thinking where to start the connection? should i use a singleton ?

Mongodb docs says that it is thread safe, so if i create a single MongoServer and single MongoDatabase classes via Singleton and per collection, I can have a method that return a collections.

Is this a bad design?

What would be a better design?

I want to use singleton to create connection to database cause I dont want to keep creating connection per thread, if there is already a persistent connection.

any experience with this?


Solution

    • Connections are pooled so if you are done with it in one thread, it will be eligible for reuse in other threads
    • You can do repository pattern down to Collection level. That's how it's done in side MongoDB Driver anyway
    • I don't really see the need to do it anyway. You can use MongoDatabase.Create(MongoUrl) method with connection string. It already does the abstraction for you in terms of server and database name