简化问题(下面是复杂且详细的问题): 当我触发此模型的构造函数时,如何使用 autofac 解析服务以获取“简单”类(模型)中的每个请求实例?(这个对象可以有多个实例,但每个实例都必须使用相同的服务实例作为请求范围)。
详细问题: 我有一个配置了 Autofac 6.2 的 .NET Framework 4.8 WebAPI。注册了多个服务,它们都是由构造函数注入的。其中一项服务是 IContext,其作用是在所有请求处理期间处理一些公共数据。在一种情况下,我需要在短时间内模仿其他上下文,因此之后需要恢复旧上下文。这种情况正在广泛使用,所以我有一些想法。我创建了一个对象:
public class TemporaryContextHolder : IDisposable
{
private int holdingMainLogID { get; set; }
private int holdingCommunicationID { get; set; }
private Type holdingRequestType { get; set; }
public IBaseInitializer _baseInitializer { get; set; }
public ICommunicationContext _communicationContext { get; set; }
public ILogger _logger { get; set; }
public TemporaryContextHolder(RequestQueue element)
{
HoldValues();
_baseInitializer.ChangeContext(element);
return this;
}
private void HoldValues()
{
holdingMainLogID = _logger.MainLogID;
holdingCommunicationID = _communicationContext.ID;
holdingRequestType = _communicationContext.RequestType;
}
public void Dispose()
{
_baseInitializer.ChangeContext(holdingMainLogID, holdingCommunicationID, holdingRequestType);
GC.SuppressFinalize(this);
}
}
该对象的作用是捕获恢复原始上下文所需的所有数据,但在该对象存在的时间段内上下文被替换。使用场景是:
foreach (var element in elementsToProcess)
{
using (var tempContext = new TemporaryContextHolder(element))
try
{
PrepareForProcessing(element);
}
catch (InvalidQueueHandlingException ex)
{
_logger.LogError(ex);
continue;
}
ProcessElement(element);
}
}
问题:我不知道如何解决 TemporaryContextHolder 中的组件。如您所见,我尝试通过这种方式通过属性注入服务:
builder.Register(x => new TemporaryContextHolder()
{
_baseInitializer = x.Resolve<IBaseInitializer>(),
_communicationContext = x.Resolve<ICommunicationContext>(),
_logger = x.Resolve<ILogger>()
}).AsSelf();
但它不起作用-> NullReferenceExc。我无法在此对象中创建新的生命周期范围,因为我需要这个现有实例。我也无法从容器中手动获取服务(未注册 TemporaryContextHolder),因为由于开发时间很长,我无法向您展示各种异常。你能告诉我如何访问这个特定的服务,或者如何以不同的方式组织代码来实现我的目标吗?谢谢。