如何在 IServiceCollection 扩展中获得依赖

How to get dependency in IServiceCollection extension

我想创建一个扩展方法,以便于注册特定的依赖项。但是那个依赖想要使用 IMemoryCache。但有可能应用程序已经注册了IMemoryCache,所以在这种情况下我想使用它。

使用该可选依赖项的最佳方法是什么?

这是class我要报名的:

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

我可以创建一个 class 以便于注册 class:

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

这个问题是,如果应用程序已经完成 services.AddMemoryCache(); 特定选项,我的注册将覆盖那些,对吗?

检查 IMemoryCache 是否已注册的最佳方法是什么,如果没有,则注册它?

或者可以将 IMemoryCache 实例提供给扩展方法?

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

不会的。

/// <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

因为 TryAdd,如果已经是 registered/added 就不会再添加了

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