Plug-n-play implementation of IResourceRepository<TResource, TId> allowing you to use MongoDB with your JsonApiDotNetCore APIs.
dotnet add package JsonApiDotNetCore.MongoDbpublic sealed class Book : MongoDbIdentifiable
{
[Attr]
public string Name { get; set; }
}public sealed class BooksController : JsonApiController<Book, string>
{
public BooksController(IJsonApiOptions options, ILoggerFactory loggerFactory, IResourceService<Book, string> resourceService)
: base(options, loggerFactory, resourceService)
{
}
}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.AddJsonApi(resources: builder =>
{
builder.Add<Book, string>();
});
services.AddJsonApiMongoDb();
services.AddResourceRepository<MongoDbRepository<Book, string>>();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseJsonApi();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
}Note: If your API project uses only MongoDB (not in combination with EF Core), then instead of registering all MongoDB resources and repositories individually, you can use:
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// ...
services.AddJsonApi(facade => facade.AddCurrentAssembly());
services.AddJsonApiMongoDb();
services.AddScoped(typeof(IResourceReadRepository<>), typeof(MongoDbRepository<>));
services.AddScoped(typeof(IResourceReadRepository<,>), typeof(MongoDbRepository<,>));
services.AddScoped(typeof(IResourceWriteRepository<>), typeof(MongoDbRepository<>));
services.AddScoped(typeof(IResourceWriteRepository<,>), typeof(MongoDbRepository<,>));
services.AddScoped(typeof(IResourceRepository<>), typeof(MongoDbRepository<>));
services.AddScoped(typeof(IResourceRepository<,>), typeof(MongoDbRepository<,>));
}
}Restore all NuGet packages with:
dotnet restoreYou don't need to have a running instance of MongoDB on your machine. To run the tests just type the following command in your terminal:
dotnet testIf you want to run the examples and explore them on your own you are going to need that running instance of MongoDB. If you have docker installed you can launch it like this:
docker run -p 27017:27017 -d mongo:latestAnd then to run the API:
dotnet run- Relationships are not supported