我在 MVC 网站上将 LightInject 与 ServiceProvider 适配器一起使用。我正在尝试将其连接到 MiniProfiler,但我运气不佳。MiniProfiler 似乎正在捕获 MVC 控制器生命周期,但没有捕获任何依赖项: Mini Profiler Image Profiling Dump(我在此屏幕截图中进行调试 - 忽略 61,744 毫秒的持续时间)
这就是我初始化容器的方式:
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
,但它为 MVC 生命周期中的每个操作进入SomeDependencyController