MongoDB Integration

This document explains how to integrate MongoDB as a database provider to ABP based applications and how to configure it.

Installation

Volo.Abp.MongoDB is the main nuget package for the MongoDB integration. Install it to your project (for a layered application, to your data/infrastructure layer):

  1. Install-Package Volo.Abp.MongoDB

Then add AbpMongoDbModule module dependency to your module:

  1. using Volo.Abp.MongoDB;
  2. using Volo.Abp.Modularity;
  3. namespace MyCompany.MyProject
  4. {
  5. [DependsOn(typeof(AbpMongoDbModule))]
  6. public class MyModule : AbpModule
  7. {
  8. //...
  9. }
  10. }

Creating a Mongo Db Context

ABP introduces Mongo Db Context concept (which is similar to Entity Framework Core’s DbContext) to make it easier to use collections and configure them. An example is shown below:

  1. public class MyDbContext : AbpMongoDbContext
  2. {
  3. public IMongoCollection<Question> Questions => Collection<Question>();
  4. public IMongoCollection<Category> Categories => Collection<Category>();
  5. protected override void CreateModel(IMongoModelBuilder modelBuilder)
  6. {
  7. base.CreateModel(modelBuilder);
  8. //Customize the configuration for your collections.
  9. }
  10. }
  • It’s derived from AbpMongoDbContext class.
  • Adds a public IMongoCollection<TEntity> property for each mongo collection. ABP uses these properties to create default repositories by default.
  • Overriding CreateModel method allows to configure collection configuration.

Configure Mapping for a Collection

ABP automatically register entities to MongoDB client library for all IMongoCollection<TEntity> properties in your DbContext. For the example above, Question and Category entities are automatically registered.

For each registered entity, it calls AutoMap() and configures known properties of your entity. For instance, if your entity implements IHasExtraProperties interface (which is already implemented for every aggregate root by default), it automatically configures ExtraProperties.

So, most of times you don’t need to explicitly configure registration for your entities. However, if you need it you can do it by overriding the CreateModel method in your DbContext. Example:

  1. protected override void CreateModel(IMongoModelBuilder modelBuilder)
  2. {
  3. base.CreateModel(modelBuilder);
  4. modelBuilder.Entity<Question>(b =>
  5. {
  6. b.CollectionName = "MyQuestions"; //Sets the collection name
  7. b.BsonMap.UnmapProperty(x => x.MyProperty); //Ignores 'MyProperty'
  8. });
  9. }

This example changes the mapped collection name to ‘MyQuestions’ in the database and ignores a property in the Question class.

If you only need to configure the collection name, you can also use [MongoCollection] attribute for the collection in your DbContext. Example:

  1. [MongoCollection("MyQuestions")] //Sets the collection name
  2. public IMongoCollection<Question> Questions => Collection<Question>();

Configure the Connection String Selection

If you have multiple databases in your application, you can configure the connection string name for your DbContext using the [ConnectionStringName] attribute. Example:

  1. [ConnectionStringName("MySecondConnString")]
  2. public class MyDbContext : AbpMongoDbContext
  3. {
  4. }

If you don’t configure, the Default connection string is used. If you configure a specific connection string name, but not define this connection string name in the application configuration then it fallbacks to the Default connection string.

Registering DbContext To Dependency Injection

Use AddAbpDbContext method in your module to register your DbContext class for dependency injection system.

  1. using Microsoft.Extensions.DependencyInjection;
  2. using Volo.Abp.MongoDB;
  3. using Volo.Abp.Modularity;
  4. namespace MyCompany.MyProject
  5. {
  6. [DependsOn(typeof(AbpMongoDbModule))]
  7. public class MyModule : AbpModule
  8. {
  9. public override void ConfigureServices(ServiceConfigurationContext context)
  10. {
  11. context.Services.AddMongoDbContext<MyDbContext>();
  12. //...
  13. }
  14. }
  15. }

Add Default Repositories

ABP can automatically create default generic repositories for the entities in your DbContext. Just use AddDefaultRepositories() option on the registration:

  1. services.AddMongoDbContext<MyDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories();
  4. });

This will create a repository for each aggregate root entity (classes derived from AggregateRoot) by default. If you want to create repositories for other entities too, then set includeAllEntities to true:

  1. services.AddMongoDbContext<MyDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories(includeAllEntities: true);
  4. });

Then you can inject and use IRepository<TEntity, TPrimaryKey> in your services. Assume that you have a Book entity with Guid primary key:

  1. public class Book : AggregateRoot<Guid>
  2. {
  3. public string Name { get; set; }
  4. public BookType Type { get; set; }
  5. }

(BookType is a simple enum here) And you want to create a new Book entity in a domain service:

  1. public class BookManager : DomainService
  2. {
  3. private readonly IRepository<Book, Guid> _bookRepository;
  4. public BookManager(IRepository<Book, Guid> bookRepository) //inject default repository
  5. {
  6. _bookRepository = bookRepository;
  7. }
  8. public async Task<Book> CreateBook(string name, BookType type)
  9. {
  10. Check.NotNullOrWhiteSpace(name, nameof(name));
  11. var book = new Book
  12. {
  13. Id = GuidGenerator.Create(),
  14. Name = name,
  15. Type = type
  16. };
  17. await _bookRepository.InsertAsync(book); //Use a standard repository method
  18. return book;
  19. }
  20. }

This sample uses InsertAsync method to insert a new entity to the database.

Add Custom Repositories

Default generic repositories are powerful enough in most cases (since they implement IQueryable). However, you may need to create a custom repository to add your own repository methods.

Assume that you want to delete all books by type. It’s suggested to define an interface for your custom repository:

  1. public interface IBookRepository : IRepository<Book, Guid>
  2. {
  3. Task DeleteBooksByType(
  4. BookType type,
  5. CancellationToken cancellationToken = default(CancellationToken)
  6. );
  7. }

You generally want to derive from the IRepository to inherit standard repository methods. However, you don’t have to. Repository interfaces are defined in the domain layer of a layered application. They are implemented in the data/infrastructure layer (MongoDB project in a startup template).

Example implementation of the IBookRepository interface:

  1. public class BookRepository :
  2. MongoDbRepository<BookStoreMongoDbContext, Book, Guid>,
  3. IBookRepository
  4. {
  5. public BookRepository(IMongoDbContextProvider<BookStoreMongoDbContext> dbContextProvider)
  6. : base(dbContextProvider)
  7. {
  8. }
  9. public async Task DeleteBooksByType(
  10. BookType type,
  11. CancellationToken cancellationToken = default(CancellationToken))
  12. {
  13. await Collection.DeleteManyAsync(
  14. Builders<Book>.Filter.Eq(b => b.Type, type),
  15. cancellationToken
  16. );
  17. }
  18. }

Now, it’s possible to inject the IBookRepository and use the DeleteBooksByType method when needed.

Override Default Generic Repository

Even if you create a custom repository, you can still inject the default generic repository (IRepository<Book, Guid> for this example). Default repository implementation will not use the class you have created.

If you want to replace default repository implementation with your custom repository, do it inside AddMongoDbContext options:

  1. context.Services.AddMongoDbContext<BookStoreMongoDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories();
  4. options.AddRepository<Book, BookRepository>(); //Replaces IRepository<Book, Guid>
  5. });

This is especially important when you want to override a base repository method to customize it. For instance, you may want to override DeleteAsync method to delete an entity in a more efficient way:

  1. public override async Task DeleteAsync(
  2. Guid id,
  3. bool autoSave = false,
  4. CancellationToken cancellationToken = default)
  5. {
  6. //TODO: Custom implementation of the delete method
  7. }

Access to the MongoDB API

In most cases, you want to hide MongoDB APIs behind a repository (this is the main purpose of the repository). However, if you want to access the MongoDB API over the repository, you can use GetDatabase() or GetCollection() extension methods. Example:

  1. public class BookService
  2. {
  3. private readonly IRepository<Book, Guid> _bookRepository;
  4. public BookService(IRepository<Book, Guid> bookRepository)
  5. {
  6. _bookRepository = bookRepository;
  7. }
  8. public void Foo()
  9. {
  10. IMongoDatabase database = _bookRepository.GetDatabase();
  11. IMongoCollection<Book> books = _bookRepository.GetCollection();
  12. }
  13. }

Important: You must reference to the Volo.Abp.MongoDB package from the project you want to access to the MongoDB API. This breaks encapsulation, but this is what you want in that case.

Advanced Topics

Set Default Repository Classes

Default generic repositories are implemented by MongoDbRepository class by default. You can create your own implementation and use it for default repository implementation.

First, define your repository classes like that:

  1. public class MyRepositoryBase<TEntity>
  2. : MongoDbRepository<BookStoreMongoDbContext, TEntity>
  3. where TEntity : class, IEntity
  4. {
  5. public MyRepositoryBase(IMongoDbContextProvider<BookStoreMongoDbContext> dbContextProvider)
  6. : base(dbContextProvider)
  7. {
  8. }
  9. }
  10. public class MyRepositoryBase<TEntity, TKey>
  11. : MongoDbRepository<BookStoreMongoDbContext, TEntity, TKey>
  12. where TEntity : class, IEntity<TKey>
  13. {
  14. public MyRepositoryBase(IMongoDbContextProvider<BookStoreMongoDbContext> dbContextProvider)
  15. : base(dbContextProvider)
  16. {
  17. }
  18. }

First one is for entities with composite keys, second one is for entities with single primary key.

It’s suggested to inherit from the MongoDbRepository class and override methods if needed. Otherwise, you will have to implement all standard repository methods manually.

Now, you can use SetDefaultRepositoryClasses option:

  1. context.Services.AddMongoDbContext<BookStoreMongoDbContext>(options =>
  2. {
  3. options.SetDefaultRepositoryClasses(
  4. typeof(MyRepositoryBase<,>),
  5. typeof(MyRepositoryBase<>)
  6. );
  7. //...
  8. });

Set Base MongoDbContext Class or Interface for Default Repositories

If your MongoDbContext inherits from another MongoDbContext or implements an interface, you can use that base class or interface as the MongoDbContext for default repositories. Example:

  1. public interface IBookStoreMongoDbContext : IAbpMongoDbContext
  2. {
  3. Collection<Book> Books { get; }
  4. }

IBookStoreMongoDbContext is implemented by the BookStoreMongoDbContext class. Then you can use generic overload of the AddDefaultRepositories:

  1. context.Services.AddMongoDbContext<BookStoreMongoDbContext>(options =>
  2. {
  3. options.AddDefaultRepositories<IBookStoreMongoDbContext>();
  4. //...
  5. });

Now, your custom BookRepository can also use the IBookStoreMongoDbContext interface:

  1. public class BookRepository
  2. : MongoDbRepository<IBookStoreMongoDbContext, Book, Guid>,
  3. IBookRepository
  4. {
  5. //...
  6. }

One advantage of using interface for a MongoDbContext is then it becomes replaceable by another implementation.

Replace Other DbContextes

Once you properly define and use an interface for a MongoDbContext , then any other implementation can replace it using the ReplaceDbContext option:

  1. context.Services.AddMongoDbContext<OtherMongoDbContext>(options =>
  2. {
  3. //...
  4. options.ReplaceDbContext<IBookStoreMongoDbContext>();
  5. });

In this example, OtherMongoDbContext implements IBookStoreMongoDbContext. This feature allows you to have multiple MongoDbContext (one per module) on development, but single MongoDbContext (implements all interfaces of all MongoDbContexts) on runtime.