LightInject - 拦截不拦截依赖项

时间:2016-11-28 15:36:24

标签: c# asp.net-mvc mvc-mini-profiler light-inject miniprofiler

我在MVC网站上使用LightInject和ServiceProvider适配器。我正在尝试将它连接到MiniProfiler,但我没有太多运气。 MiniProfiler似乎正在捕获MVC Controller Lifecycle,但不是任何依赖项: 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生命周期中的每个操作进入

1 个答案:

答案 0 :(得分:0)

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

来自LightInject的文档:

  

任何标记为虚拟的成员都可以被截获。

我错过了那一部分。希望这可以帮助将来的某个人。