After reading this post I can understand the differences between AddTransient
,AddScoped
and AddSingleton
however, I am unable to see the p
I've seen the "just use AddTransient
" view, but I don't agree.
I hate allocating things when I don't have to, so if I know I'm creating something that's thread-safe, or that I have explicit documentation that having a singleton instance is the expected usage, then I'm creating a singleton.
Here's the ApplicationInsights TelemetryClient instance as a singleton. Their documentation says this works.
telemetryClient = new TelemetryClient(TelemetryConfiguration.Active);
services.AddSingleton(telemetryClient);
In this project I use Azure Table Storage as well, and I've found that creating a CloudTableClient as a singleton works just fine. I don't need to keep creating instances of it for every request.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Configuration.GetValue("storageAccountConnectionString"));
CloudTableClient someTableClient = storageAccount.CreateCloudTableClient();
services.AddSingleton(someTableClient);
In some sense, it's the equivalent of a class's readonly static property, for instance:
public static readonly CloudTableClient cloudTableClient = new CloudTableClient(...);
... there's only one instance of it in the whole application, but by using services.AddSingleton
we get direct access to it using Dependency Injection.
An example of AddScoped
for me is that I want to embed the JavaScript that I need to get Application Insights into a web page, but I use Content-Security-Policy, so I need to put a nonce on any on-page JavaScript. I have a little bit of code that helps me do it.
services.AddScoped();
I haven't found a need to use AddTransient
for anything yet. It could be that I don't think of things that I have to create, every time I need them, as "services"... they're just variables that I new up. In some sense, AddTransient
is a hidden use of the Factory pattern... instead of calling a static MyServiceFactory.Create()
function, you have Dependency Injection (effectively) do the same thing for you.