简体   繁体   中英

LightInject - Interception not intercepting dependencies

I'm using LightInject with the ServiceProvider adapter on an MVC website. I'm trying to wire it into MiniProfiler, but I'm not having much luck. MiniProfiler seems to be capturing the MVC Controller Lifecycle, but not any of the dependencies: Mini Profiler Image Profiling Dump (I was debugging during this screenshot - ignore the 61,744 ms duration)

This is how I'm initializing the container:

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;
}

The interceptor looks like this:

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();
        }
    }
}

This is the controller and test dependency:

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);
    }
}

I threw a breakpoint in the interceptor code. It never enters the interceptor for anything for SomeDependency , but it enters for every action in the MVC lifecycle for SomeDependencyController

I figured it out. I needed to make the method virtual .

From LightInject's documentation:

Any member that is marked as virtual can be intercepted.

I missed that part. Hopefully this helps someone in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM