【问题标题】:C# ASP.NET Dependacy injection: Determine which 'service' is using another 'service'C# ASP.NET 依赖注入:确定哪个 \'service\' 正在使用另一个 \'service\'
【发布时间】:2022-08-10 16:52:46
【问题描述】:

我们正在使用 ASP.NET 核心并遇到问题,即某些注册服务(来自第三方库)请求已弃用的特定“服务”(基于接口)。

问题是我们不知道哪些库正在使用这个已弃用的服务接口。

到目前为止,我们所做的是:

  • 为服务接口创建自定义实现
  • 并向 DI 注册此自定义实现(类)
// Registration
services.AddTransient<IServiceInterface>((services) => new CustomCustomService(Log.Logger));

// Custom implementation
internal class CustomService : IServiceInterface
{
  public CustomService (ILogger logger)
  {
    logger.Warning(\"!!! CustomService is still being used !!!\");
  }
}

所以现在我们可以看到不需要的服务正在“某处”使用。

但是是否有可能以某种方式检测为哪个服务创建了已弃用的服务?

我尝试使用列出堆栈跟踪

    var st = new System.Diagnostics.StackTrace();
    logger.Warning(\"!!! CustomService is still being used !!!\" + Environment.NewLine + \"{stacktrace}\", st.ToString());

但这似乎并没有提供有关使用已弃用服务的服务的信息......

  • 为什么不从 ServiceCollection 中完全删除注册?这将允许应用程序快速失败并给您一个异常消息,该消息准确说明哪个组件依赖于缺少的注册。因为不这样做,意味着您需要向CustomCustomService 提供有关其消费者的上下文信息,而这在 MS.DI 中是很难实现的。
  • 好的,dit 这个,我得到了一个出现问题的项目。但现在我不确定我是否不依赖从另一个服务中删除的服务。

标签: c# asp.net dependency-injection


【解决方案1】:

您可以尝试以下方法:

var registrationsDependingOnMyService =
    from descriptor in services
    where descriptor.ImplementationType != null
    let dependencies =
        from ctor in descriptor.ImplementationType!.GetConstructors()
        from param in ctor.GetParameters()
        select param.ParameterType
    where dependencies.Contains(typeof(IServiceInterface))
    select descriptor;

这将在IServiceCollection 中查询其实现类型具有IServiceInterface 类型的构造函数参数的注册。

这可能不是一个防弹的解决方案,因为类型或注册可能更偷偷地依赖于服务集合(例如,通过从注册委托中回调IServiceProvider),但这可能是您可以使用 MS.DI 做的最好的事情.

【讨论】:

    【解决方案2】:

    所以基本上 - 正如预期的那样 - 不可能确切地知道哪些库(您没有代码)使用某种依赖关系。

    这只是反复试验;)

    感谢大家的想法。

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 2017-04-18
      • 2019-06-08
      • 2019-05-26
      • 2016-02-16
      • 2018-11-20
      • 2023-03-03
      • 2019-01-19
      相关资源
      最近更新 更多