skip to Main Content

We’re using ASP.NET core and are running into the problem, that some registered services (from third-party libraries) request a specific ‘service’ (based on an interface) that has been deprecated.

The problem is that we don’t know which libraries are using this deprecated service interface.

What we’ve done so far is:

  • create a custom implementation for the service interface
  • and registered this custom implementation (class) with 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 !!!");
  }
}

So now we can see that the unwanted service is being used ‘somewhere’.

But is it in some way possible to detect for which service the deprecated service has been created?

I’ve tried listing the stack trace using

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

But that doesn’t seem to give information about the service using the deprecated service…

2

Answers


  1. Chosen as BEST ANSWER

    So basically - as expected - it's not possible to exactly know which libraries (for which you don't have the code) use a certain dependency.

    It's just trial and error ;)

    Thanks for the ideas everyone.


  2. You can try the following:

    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;
    

    This will query the IServiceCollection for registrations whose implementation type have a constructor argument of type IServiceInterface.

    This might not be a bulletproof solution, as types or registrations can more sneakily depend on the service collection (e.g. by calling back into the IServiceProvider from within a registration delegate), but this is likely the best you can do with MS.DI.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search