简单喷油器跟踪时间

Simple Injector tracing times

有没有一种方法可以跟踪通过简单注入器和构造函数的 IoC 解析实例所花费的时间?

我的意思是跟踪级别的东西

谢谢

在 Simple Injector 中解析实例非常快,应该永远不会成为问题,除非 your constructors do too much.

尽管如此,可以使用以下扩展方法添加跟踪(适用于 Simple Injector v2.x 及更高版本):

public static void ApplyInterceptor(
    this ContainerOptions options, Func<Func<object>, object> interceptor)
{
    options.Container.ExpressionBuilding += (s, e) =>
    {
        var factory = Expression.Lambda(typeof(Func<object>), e.Expression).Compile();

        e.Expression = Expression.Convert(
            Expression.Invoke(
                Expression.Constant(interceptor),
                Expression.Constant(factory)),
            e.Expression.Type);
    };
}

可以调用这个ApplyInterceptor扩展方法来拦截容器产生的所有类型的创建,例如添加这个监控行为:

container.Options.ApplyInterceptor(producer =>
{
    var watch = Stopwatch.StartNew();
    object instance = null;
    try
    {
        instance = producer();
        return instance;
    }
    finally
    {
        watch.Stop();
        if (watch.ElapsedMilliseconds > 50)
        {
            string name = instance.GetType().ToFriendlyName();
            Console.WriteLine(
                $"WARNING: {name} took {watch.ElapsedMilliseconds} ms. to resolve.");
        }
    }
})

WARNING: This interceptor gets applied to all registrations in Simple Injector and could severely impact runtime performance, so make sure you only add this during debug builds or when the debugger is attached, to make sure you don't impact runtime performance.