Dynamically add embedded database via dependency injection

96 views Asked by At

I'm building an application which is using a project like approach. Like in e.g. Visual Studio one creates a new project. I need a project name and a location. For every project an embedded database should be created in the respective location. I'm using LiteDB.

At the moment I register the DB vis DI:

serviceCollection.AddSingleton<ILiteDatabase>(new LiteDatabase(path.Value));

path.Value is the appsettings.json.

And in my persistence service I can just use it like:

public class PersistenceService
{
    private readonly LiteDB.ILiteDatabase liteDatabase;

    public PersistenceService(LiteDB.ILiteDatabase liteDatabase)
    {
        this.liteDatabase = liteDatabase;
    }
}

The approach with path.Value from appsettings.json doesn't work as the project is getting created after the app is initialized. I want to create a new project and create based on the name and location a new LiteDB file which should be registred in the serviceCollection. But that does not work as I can't change the serviceCollection afterwards.

One approach would be to create the LiteDB in my PersistenceService but that would make testing more complicated.

What is the best way to do such things?

0

There are 0 answers