c# - 如何在 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 实例赋予扩展方法?
解决方案
这个问题是,如果应用程序已经完成
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
,如果它已经注册/添加它不会再次添加它
如果服务类型尚未注册,则将指定的描述符添加到集合中。
推荐阅读
- node.js - 在 NODEJS 中使用超链接和按钮更改路线的正确方法是什么?
- c++ - 包含 Bazel http_file 下载的文件
- python - 如何正确设置 Python 套接字服务器
- google-colaboratory - 在 Google Colab 中设置环境变量
- go - 在golang中迭代多个返回
- kotlin - 由于源代码中的多个实现,异步不会编译
- r - 在 stringr 中提取所有内容直到第三个句点
- java - Xerces v2.12.0 XML Schema 1.1 验证
- python - 如何摆脱 Python sympy 中的垂直渐近线?
- enterprise-architect - Enterprise Architect:在创建实例时从初始属性值设置运行状态