I implemented a class EUMemberChecker
which is responsible of checking if a country is a member of the EU.
In order to do its job, the class contains a method public bool IsEUMember(string country)
.
The data used to check if a country is a member of the EU is stored in a PostgreSQL database table.
I want to make this class available via DI by adding it as a singleton service via AddSingleton
. The reason for this is that it should only load the EU members from the database once on application startup. If I would add this class via AddScoped
, every single instance of it would need to have its own list of EU members loaded from the database, which would be quite an overhead in my opinion.
My problem is that I cannot add this class as a singleton because it uses my DbContext
which is added as a scoped service. By doing it anyway, it causes the runtime error Dependency ...DatabaseContext {ReturnDefault} as parameter "context" reuse CurrentScopeReuse {Lifespan=100} lifespan shorter than its parent's: singleton ... {ReturnDefault} as parameter ...
.
Therefore, it seems like I have to add my class as a scoped service, resulting in an additional database call to load the EU member countries for every instance of the class.
Am I applying the Single Responsibility Principle incorrectly here or how can I get around this problem? How can I ensure that the EU members are not loaded from the database multiple times for no good reason?