Search code examples
mongodbonion-architecture

MongoDB: using onion architecture, does my domain/core layer need to reference the MongoDB dlls?


MongoDB has its own ObjectId type that it uses as the default primary key. I'm trying to set up an application designed using Onion Architecture with MongoDB as the persistence engine in the infrastructure layer. If my POCO classes are defined in my domain layer but use MongoDB's ObjectID type for primary keys, will that force me to add MongoDB as a dependency on my domain layer?


Solution

  • You should not need a reference to MongoDB anywhere except the outer-most layer. In onion architecture, data persistence is considered infrastructure. I would have MongoDB be part of a repository implementation that implements repository interfaces defined in the domain model.

    MongoDB documents have an _id field that uniquely identifies it. See here:

    The _id value may be of any type, other than arrays, so long as it is a unique. If your document has a natural primary key that is immutable we recommend you use that in _id instead of the automatically generated ids.

    Don't let your persistence mechanism push you around!