【发布时间】:2014-10-16 01:46:37
【问题描述】:
我在使用 Autofac 时遇到了严重的内存泄漏问题,我想我可能已经解决了。但是,我很好奇StatsRefreshMessageHandler 类中注入的服务StatsService 是否使用调用它的Helpers 类的生命周期范围。
注册服务
builder.RegisterType<StatsService>().InstancePerLifetimeScope();
我的助手类被注入了一个生命周期,然后它会调用适当的消息处理程序。在此示例中,它将是 StatsRefreshMessageHandler
public class Helpers
{
private ILifetimeScope _lifetimeScope;
private ILifetimeScope _lifetimeScope;
public Helpers(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
}
public void ProcessMessage<T>(T message) where T : class
{
//Voodoo to construct the right message handler type
Type handlerType = typeof(IMessageHandler<>);
Type[] typeArgs = { message.GetType() };
Type constructed = handlerType.MakeGenericType(typeArgs);
//Handle the message
using (var messageScope = _lifetimeScope.BeginLifetimeScope())
{
var handler = messageScope.Resolve(constructed);
var methodInfo = constructed.GetMethod("Handle");
//this is where it call the message handler
methodInfo.Invoke(handler, new[] { message });
}
}
}
下面的类 (StatsRefreshMessageHandler) 使用标准的 IOC 注入......但是,这里的问题是 StatsService 从哪里解决?我假设它来自调用者的生命周期范围(Helpers),但如果它是从根内核解决的,那么我仍然会遇到问题。
public class StatsRefreshMessageHandler : IMessageHandler<StatsRefreshMessage>
{
private readonly StatsService _statsService;
public StatsRefreshMessageHandler(StatsService statsService)
{
_statsService = statsService;
}
public void Handle(StatsRefreshMessage message)
{
_statsService.UpdateStatsCache(DateTime.UtcNow);
Console.WriteLine("DONE STATS");
}
}
【问题讨论】: