Dennis
Dennis

Reputation: 215

ASP.NET Core API Service Lifetime

I have a service in my ASP.NET Core (2.1) app that needs to be a singleton, as I have information that I need to keep in memory over the entire lifetime of the app. This service has dependencies to some repositories that do not need to be singletons and I would like to define them as transient, but ASP.NET Core does not like it when you inject a transient dependency into a singleton service. I can kind of understand why, though I'm still new to this stuff. But my question is: what is the correct way to handle this situation? I can just make my repositories singletons and that will satisfy ASP.NET Core. Or I could try using a service provider to get the repositories just when they're needed. But I'm looking for a "best practices" approach. Any advice would be greatly appreciated.

Thanks!

Upvotes: 3

Views: 2045

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239220

As @CamiloTerevinto indicated in the comments, it's difficult to give you precise guidance without knowing more about what you're actually doing. I can tell you some general things, though.

First, singletons come in two forms: things that are so simplistic there's no point in having multiple copies or things that are so complex it would be burdensome to have multiple copies. Anything on the spectrum in between should likely be request-scoped or transient. Importantly, keeping data in-memory, is not a valid reason to use singleton scope. You can use memory cache (or even better: distributed cache) from a object with any lifetime. needing long-lived state on an object is pretty much always a signal of bad class design.

Second, ironically, if anything, your repositories should actually be the ones with a singleton scope. A repository generally requires a database connection and that should be as long-lived as possible or practical.

However, don't just go ahead an make your repositories singletons and call it a day. You should stop first and evaluate if your current singleton class really should in fact be in that scope. Then, depending on your application, it might actually be better to have the repos request-scoped, which still means you can't inject them directly.

Upvotes: 4

Related Questions