My Stactive project is now functional. It can log ASP.NET Core requests to a MongoDb database. Stactive is a middleware, which in future will be available as a Nuget package. It will support few storing options - as separate plugins - Nuget packages. To make it happen, I needed to implement MongoDb support as a plugin and I decided it might be worth to share how it’s done.
- Why plugins
- Core project
- Stactive.MongoDbPersistence project
- Plugin registration
- Using the plugin
You could ask, why I don’t implement everything in one package. The answer is simple - dependencies. If you don’t want Stactive to save anything to MongoDb, why should you add a dependency to MongoClient library? Same with ElasticSearch or MS SQL. Plugins allow to selectively add dependencies to your application.
So far, all of the Stactive code was stored in one project. Because I don’t want my MongoDb persistence library to have a dependency from ASP.NET, I needed to create a Stactive.Core project and move all the models there. I have also added an
IPersistance interface there, which all the persistence libraries will implement:
For now, we only log request information, so it only has this one method. In future, I will be adding more here.
This is the project of my new library:
As you see, it only has a few dependencies:
- Dependency Injection framework from ASP.NET Core
- MongoDb driver
Nothing more is needed for it to perform its tasks.
I wanted to be able to register this plugin like you do with other middlewares:
This is the part of the
Startup class from my sample project. It uses both
Stactive.MongoDbPersistence dependencies. Thanks to the second one, it has access to
StactiveMongoRegistration class, which is responsible for configuring the plugin:
The first line registers
MongoDbPersistence class as an implementation of my persistence interface. This way, Stactive will be able to inject it in the constructor. Then you can see the use of
This class allows setting all the options relevant to the plugin. It uses an instance of this class to initialize
StactiveMongoDb, which contains MongoDb client object:
Using the plugin
Because I have registered the
MongoDbPersistence class with the DependencyInjection, everything I now have to do in the Stactive project is to request it in the constructor:
You can see how the constructor expects
IEnumerable<IPersistence> - this will provide all implementations of the interface, which are then used later in the
Sometimes, you see nuget libraries, which have a very long list of dependencies. If you want to use such library, you have to install them. Even though, you might need only one. An answer to such problem is partitioning the libraries. One way of doing that is by using plugins. I think it’s very good option and I hope I made this concept more clear today.
As always, you can find the code in the Stactive repository.