mongodb-generic-repository icon indicating copy to clipboard operation
mongodb-generic-repository copied to clipboard

Scoped repository/multitenancy

Open attilabicsko opened this issue 1 year ago • 2 comments

Hi! What performance reprecussions should I expect when the repository is configured to be scoped instead of singleton?

In my scenario, I'm trying to implement multitenancy (DB per tenant strategy) with AspNetCore.Identity.MongoDbCore, and I'd like to use a tenant-specific, scoped IMongoDbContext. To make it work I had to change both the IMongoDbContext and IMongoRepository services scoped.

My solution works, and I don't see any I/O bound operations in the Repository initialization, so I'm wondering why you advise it being a singleton. I'm new to MongoDB, so I may be missing something. Thank you in advance!

attilabicsko avatar Apr 30 '23 00:04 attilabicsko

I suspect the advice relates to the connection pooling in the mongo driver itself.

Issues with connection exhaustion normally only show themselves when a system is having to serve many requests at once. Registering as Scoped results in spinning up a new connection pool with every request being processed by your server. This will slow the processing of each request and if the server is taking a lot of traffic it could quickly run into re-source constraints.

As a suggestion to solve the scenario of a multi-tenant system with a database per tenant, it might be better to build and register a IMongoRepositoryFactory that creates the IMongoRepository singletons and caches the instances against some reference for each tenant. That way the problems that a scoped registration would give can be avoided.

blacktau avatar Jul 22 '23 11:07 blacktau

@attilabicsko - I am trying to do the same thing. Did you implement it successfully? How did you made builder.Services.AddIdentity<ApplicationUser, ApplicationRole>() .AddMongoDbStores<>(...) to work? Since inside this extension method it always assumes one connection strings. To me it feels like I have to change certain parts of AspNetCore.Identity.MongoDbCore as well.

Any thoughts?

mkgn avatar Dec 04 '23 02:12 mkgn