LightInject - 拦截不拦截依赖

LightInject - Interception not intercepting dependencies

我在 MVC 网站上使用 LightInject 和 ServiceProvider 适配器。我正在尝试将其连接到 MiniProfiler,但运气不佳。 MiniProfiler 似乎正在捕获 MVC 控制器生命周期,但不是任何依赖项: Mini Profiler Image Profiling Dump (I was debugging during this screenshot - ignore the 61,744 ms duration)

这是我初始化容器的方式:

protected override IServiceProvider BuildServiceProvider(IServiceCollection serviceCollection)
{
    var container = new ServiceContainer();
    container.Register<IInterceptor, MiniProfilerInterceptor>();
    foreach (var descriptor in serviceCollection)
    {
        if (descriptor.ServiceType.AssemblyQualifiedName.StartsWith("ProjectName"))
        {
            container.Intercept(s => s.ServiceType == descriptor.ServiceType, i => i.GetInstance<IInterceptor>());
        }
    }
    var serviceProvider = container.CreateServiceProvider(serviceCollection);
    return serviceProvider;
}

拦截器如下所示:

public class MiniProfilerInterceptor : IInterceptor
{
    public object Invoke(IInvocationInfo invocation)
    {
        var profiler = MiniProfiler.Current;
        var returnType = invocation.Method.ReturnType;
        using (profiler.Step(invocation.Proxy.GetType().Name + ":" + invocation.Method.Name))
        {
            return invocation.Proceed();
        }
    }
}

这是控制器和测试依赖项:

public class SomeDependencyController : Controller
{
    private readonly SomeDependency _dependency;

    public SomeDependencyController(SomeDependency dependency)
    {
        _dependency = dependency;
    }
    public MvcHtmlString DoSomething()
    {
        _dependency.DoSomething();
        return new MvcHtmlString("Did it");
    }
    public ActionResult DoRender()
    {
        _dependency.DoSomething();
        return View("DoRender");
    }
}

public class SomeDependency
{
    public void DoSomething()
    {
        Thread.Sleep(1000);
    }
}

我在拦截器代码中设置了一个断点。它永远不会为 SomeDependency 的任何内容进入拦截器,但它会为 SomeDependencyController

的 MVC 生命周期中的每个操作进入

我明白了。我需要制作方法 virtual

来自 LightInject 的文档:

Any member that is marked as virtual can be intercepted.

我错过了那部分。希望这对将来的人有帮助。