我最近开始为一个拥有庞大代码库的组织工作,该组织使用Autofac作为他们选择的DI容器。
不幸的是,并不是所有的开发人员都在编写类时遵循最佳实践,这意味着他们有时会调用外部服务,并在其构造函数的内部 做其他繁重的工作。这是DI代码的味道,如injection constructors should be simple。
考虑到应用程序的大小以及使用代码的开发人员的数量,不可能一一审查所有现有的类。相反,我想编写一个集成测试,该测试可以连接到Autofac管道并报告解决方案,需要花费相当长的时间。
我将如何实现这样的目标? Autofac会暴露哪些拦截点以进行此测量?
使用Simple Injector,我可以通过注册解析拦截器来实现此目标,如以下示例所示:
container.Options.RegisterResolveInterceptor((context, producer) =>
{
var watch = Stopwatch.StartNew();
try
{
return producer.Invoke();
}
finally
{
if (watch.TotalElapsedMiliseconds > THRESHOLD)
{
Console.WriteLine(
$"Resolving {context.Registration.ImplementationType} " +
$"took {watch.TotalElapsedMiliseconds} ms.");
}
}
},
c => true);
如何使用Autofac获得相似的结果?
答案 0 :(得分:5)
使用Autofac模块,您可以挂接Preparing
和Activating
事件:
Autofac注册:
builder.RegisterModule<TimeMeasuringResolveModule>();
TimeMeasuringResolveModule:
public class TimeMeasuringResolveModule : Module
{
private readonly ResolveInfo _current;
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry, IComponentRegistration registration)
{
registration.Preparing += Registration_Preparing;
registration.Activating += Registration_Activating;
base.AttachToComponentRegistration(componentRegistry, registration);
}
private void Registration_Preparing(object sender, PreparingEventArgs e)
{
// Called before resolving type
_current = new ResolveInfo(e.Component.Activator.LimitType, _current);
}
private void Registration_Activating(object sender, ActivatingEventArgs<object> e)
{
// Called when type is constructed
var current = _current;
current.MarkComponentAsResolved();
_current = current.Parent;
if (current.Parent == null)
{
ResolveInfoVisualizer.VisualizeGraph(current);
}
}
}
ResolveInfo:
public sealed class ResolveInfo
{
private Stopwatch _watch = Stopwatch.StartNew();
public ResolveInfo(Type componentType, ResolveInfo parent)
{
ComponentType = componentType;
Parent = parent;
Dependencies = new List<ResolveInfo>(4);
if (parent != null) parent.Dependencies.Add(this);
}
public Type ComponentType { get; }
public List<ResolveInfo> Dependencies { get; }
// Time it took to create the type including its dependencies
public TimeSpan ResolveTime { get; private set; }
// Time it took to create the type excluding its dependencies
public TimeSpan CreationTime { get; private set; }
public ResolveInfo Parent { get; }
public void MarkComponentAsResolved()
{
ResolveTime = _watch.Elapsed;
CreationTime = ResolveTime;
foreach (var dependency in this.Dependencies)
{
CreationTime -= dependency.ResolveTime;
}
}
}
ResolveInfoVisualizer:
public static class ResolveInfoVisualizer
{
public static void VisualizeGraph(ResolveInfo node, int depth = 0)
{
Debug.WriteLine(
$"{new string(' ', depth * 3)}" +
$"{node.ComponentType.FullName} " +
$"({node.ResolveTime.TotalMilliseconds.ToString("F1")} ms. / " +
$"/ {node.CreationTime.TotalMilliseconds.ToString("F1")} ms.));
foreach (var dependency in node.Dependencies)
{
VisualizeGraph(dependency, depth + 1);
}
}
}
通常应在单元测试中使用输出,而不是登录到“调试”窗口。请注意,此TimeMeasuringResolveModule
是不是线程安全的。考虑到该模块的性能开销,您只能将其用作单个集成测试的一部分。
还请注意,尽管此模块确实生成对象图,但它不输出代表性的对象图,而仅包含在该解析过程中实际激活的对象。例如,已经初始化的单例将不会显示在图中,因为它们实际上是无操作的。为了可视化真实的对象图,应使用其他方法。