Reputation: 3907
is there a way I can keep track of how much time is taken to resolve an instance via Simple Injector and Constructor's IoC?
I mean something at trace level
Thanks
Upvotes: 1
Views: 210
Reputation: 172606
Resolving instances in Simple Injector is blazingly fast, and should never be a problem, unless your constructors do too much.
Nonetheless, adding tracing can be done using the following extension method (works for Simple Injector v2.x and beyond):
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);
};
}
This ApplyInterceptor
extension method can be called to intercept the creation of all types produced by the container, for instance to add this monitoring behavior:
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.
Upvotes: 5