user369117
user369117

Reputation: 825

How to get dependency in IServiceCollection extension

I would like to create an extension method to make it easy to register a specific dependency. But that dependency wants to use IMemoryCache. But it is possible that the application has already registered IMemoryCache, so in that case I would like to use that.

What's the best way to do use that optional dependency?

This is the class I want to register:

public class MyThing : IMyThing
{
   public MyThing(IMemoryCache cache)
   {
      ...
   }
   ...
}

I can create a class to make it easy to register the class:

public static class MyThingRegistration
{
   public static void AddMyThing(this IServiceCollection services)
   {
      services.AddScoped<IMyThing, MyThing>();
      services.AddMemoryCache(); <--------- This might be an issue
   }
}

This issue is that if the application has already done services.AddMemoryCache(); with specific options, my registration will override those, right?

What's the best way to check if IMemoryCache is already registered, and if not, then register it?

Or maybe and IMemoryCache instance can be given to the extension method?

Upvotes: 2

Views: 853

Answers (1)

Nkosi
Nkosi

Reputation: 247088

This issue is that if the application has already done services.AddMemoryCache(); with specific options, my registration will override those, right?

No it wont.

/// <summary>
/// Adds a non distributed in memory implementation of <see cref="IMemoryCache"/> to the
/// <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddMemoryCache(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddOptions();
    services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());

    return services;
}

Source code

Because of the TryAdd, if it is already registered/added it wont add it again

Adds the specified descriptor to the collection if the service type hasn't already been registered.

Upvotes: 3

Related Questions