Skip to content

json-api-dotnet/JsonApiDotNetCore.MongoDb

Repository files navigation

MongoDB support for JsonApiDotNetCore

Plug-n-play implementation of IResourceRepository<TResource, TId> allowing you to use MongoDB with your JsonApiDotNetCore APIs.

Build status NuGet

Installation and Usage

dotnet add package JsonApiDotNetCore.MongoDb

Models

public sealed class Book : IIdentifiable<string>
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    [Attr]
    public string Id { get; set; }

    [Attr]
    public string Name { get; set; }

    [BsonIgnore]
    public string StringId { get => Id; set => Id = value; }
}

Controllers

public sealed class BooksController : JsonApiController<Book, string>
{
    public BooksController(IJsonApiOptions options, ILoggerFactory loggerFactory, IResourceService<Book, string> resourceService)
        : base(options, loggerFactory, resourceService)
    {
    }
}

Middleware

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IMongoDatabase>(sp =>
        {
            var client = new MongoClient(Configuration.GetSection("DatabaseSettings:ConnectionString").Value);
            return client.GetDatabase(Configuration.GetSection("DatabaseSettings:Database").Value);
        });

        services.AddResourceRepository<MongoDbRepository<Book>>();
        
        services.AddJsonApi(resources: builder =>
        {
            builder.Add<Book, string>();
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseJsonApi();
        app.UseEndpoints(endpoints => endpoints.MapControllers());
    }
}

Limitations

  • Relationships are not supported