2

I'm adding a service to the IServiceCollection in my startup as Scoped:

    public void ConfigureServices(IServiceCollection services)
    {
          services.AddScoped<IEmailService, EmailService>();
    }

If I were to add a static property to my EmailService implementation, does that mean that my property is not garbage collected and remains in memory even though my EmailService has gone out of scope after my request ends?

I'm looking at some code that has a static property that holds a bearer token. It appears that this token remains in memory once it is set and stays there until my AppPool refreshes after a day.

ScottG
  • 10,711
  • 25
  • 82
  • 111
  • Possible duplicate of [Do static members ever get garbage collected?](https://stackoverflow.com/questions/6600093/do-static-members-ever-get-garbage-collected) – dugas Dec 14 '18 at 19:55
  • 2
    like Jon Skeet says there, static members are not associated with the instance, they are with the type. – MrVoid Dec 14 '18 at 20:12
  • You can have a singleton service that holds your important configuration values (or secrets) and inject that into your scoped service. There's never a reason to use static fields or properties with dependency inject/inversion of control (containers9 – Tseng Dec 14 '18 at 20:38
  • thanks, I didn't think so. I am going to follow your approach. Thanks Tseng. – ScottG Dec 14 '18 at 21:15

2 Answers2

2

does that mean that my property is not garbage collected and remains in memory even though my EmailService has gone out of scope after my request ends?

yes

see here:

"static members are associated with the Type, which is associated with the AppDomain it's loaded in .. Note that there doesn't [even] have to be any instances .. for the class to be initialized"

kofifus
  • 17,260
  • 17
  • 99
  • 173
0

Use a singleton service instead of static property

//Create a class for your static items.
public class CachedItems
{
    public string BearerToken { get; set; }
}

//add this as a singleton to startup.cs file
services.AddSingleton<CachedItems>();

//inject your class to wherever you need
public class YourScopedService : BaseService
{
    private readonly CachedItems _cachedItems;

    public ProductService(CachedItems cachedItems)
    {
        _cachedItems = cachedItems;
    }
}
Omer
  • 8,194
  • 13
  • 74
  • 92