首页 > 解决方案 > 如何在 IServiceCollection 扩展中获取依赖项

问题描述

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

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

这是我要注册的课程:

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

我可以创建一个类以方便注册该类:

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 实例赋予扩展方法?

标签: c#.net-coredependency-injection

解决方案


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

不,它不会。

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

源代码

因为TryAdd,如果它已经注册/添加它不会再次添加它

如果服务类型尚未注册,则将指定的描述符添加到集合中。


推荐阅读