2015-05-08 112 views

回答

5

解決在簡單的注射器情況下是極快的,和不應該是一個問題,除非your constructors do too much

儘管如此,添加跟蹤是微不足道的,可以如下(爲V2.8及以上)完成:

container.Options.RegisterResolveInterceptor((context, producer) => { 
     var watch = Stopwatch.StartNew(); 
     try { 
      return producer(); 
     } finally { 
      watch.Stop(); 
      if (watch.ElapsedMilliseconds > 50) { 
       Console.WriteLine(
        "Resolving {0} took {1} ms. Object graph: {2}", 
        context.Producer.ServiceType.Name, 
        watch.ElapsedMilliseconds, 
        context.Producer.VisualizeObjectGraph()); 
      } 
     } 
    }, 
    // Apply to every registration 
    context => true); 

RegisterResolveInterceptor方法允許你攔截對GetInstanceGetAllInstances直接調用。所以註冊的委託將被應用到最外層的對象上,而不是它的依賴關係上。

如果您需要更細粒度的信息,例如所花費的時間來創建一個特定的依賴,你可以連接到ExpressionBuilt事件如下:

container.ExpressionBuilt += (s, e) => 
{ 
    MethodInfo monitorMethod = 
     this.GetType().GetMethod("Monitor").MakeGenericMethod(e.RegisteredServiceType); 

    Delegate producer = Expression.Lambda(
     typeof(Func<>).MakeGenericType(e.RegisteredServiceType), e.Expression) 
     .Compile(); 

    e.Expression = Expression.Call(monitorMethod, Expression.Constant(producer)); 
}; 


// Method somewhere else in the same class 
public static T Monitor<T>(Func<T> producer) { 
    var watch = Stopwatch.StartNew(); 
    try { 
     T instance = producer(); 
     return instance; 
    } finally { 
     watch.Stop(); 
     if (watch.ElapsedMilliseconds > 50) { ... } 
    } 
} 
相關問題