Autofac 使用生命周期范围作为处理工作单元期间创建的所有组件的一种方式。虽然这是一个强大的功能,但很容易编写不能正确处理生命周期范围的代码,这会导致跟踪的一次性数量随着时间的推移而增长:实际上是内存泄漏。
有没有办法监控生命周期范围在任何时间点跟踪的一次性对象的数量。我有兴趣编写工具来帮助我找到与未正确地将一次性用品分配给工作单元相关的问题。目前我使用内存分析器工具来查找泄漏,但这是一项相当繁重的工作。
我查看了 ILifetimeScope 的公共接口,但没有看到任何有用的东西。
不幸的是,分析是 Autofac 目前的弱点之一。有一个存储库,其中在分析包上开始了一些工作 https://github.com/autofac/autofac-analysis但肯定存在一些差距 - 例如,您可以跟踪对象何时活性你可以看到什么时候生命周期范围已处置,但您无法追踪单个objects作为范围的一部分进行处理。只是没有任何活动。
一个非常简单的激活跟踪模块如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Autofac.Core;
namespace DiagnosticDemo
{
public class TrackingModule : Module
{
private readonly IDictionary<Type, int> _activations = new Dictionary<Type, int>();
private readonly object _syncRoot = new object();
public void WriteActivations()
{
foreach (var pair in this._activations.Where(p => p.Value > 0))
{
Console.WriteLine("* {0} = {1}", pair.Key, pair.Value);
}
}
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
if (registration.Ownership == InstanceOwnership.OwnedByLifetimeScope)
{
registration.Activated += this.OnRegistrationActivated;
}
}
private void OnRegistrationActivated(
object sender,
ActivatedEventArgs<object> e)
{
if (e.Instance is IDisposable)
{
var type = e.Instance.GetType();
Console.WriteLine("Activating {0}", type);
lock (this._syncRoot)
{
if (this._activations.ContainsKey(type))
{
this._activations[type]++;
}
else
{
this._activations[type] = 1;
}
}
}
}
}
}
你会像这样使用它:
static void Main(string[] args)
{
var trackingModule = new TrackingModule();
var builder = new ContainerBuilder();
// Register types, then register the module
builder.RegisterType<Consumer>().As<IConsumer>();
builder.RegisterType<DisposableDependency>().As<IDependency>();
builder.RegisterType<NonDisposableDependency>().As<IDependency>();
builder.RegisterModule(trackingModule);
var container = builder.Build();
// Do whatever it is you want to do...
using (var scope = container.BeginLifetimeScope())
{
scope.Resolve<IConsumer>();
}
// Dump data
Console.WriteLine("Activation totals:");
trackingModule.WriteActivations();
}
但是,这不会告诉您哪些项目weren't处置,我想这就是你想知道的。不过,它可能会给你一些想法,或者至少有一点帮助。
如果您有兴趣帮助改进 Autofac 中的分析,我们很乐意采取 PR 或具体设计想法来了解如何改进 https://github.com/autofac/Autofac/issues.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)