我很可能在这里误解了一些东西,所以也许这里有一个简单的答案,但我目前正在摸不着头脑。
我有一个实现 IUnitOfWork 的 UnitOfWork 类(是的,我知道)。工作单元的构造函数采用 IPrincipalFactory。TResponder 是图表的顶层,它采用 IUnitOfWork。
我正在尝试将 ApplicationPrincipalFactory 注册为生命周期范围内的特定实例......它依赖于传递给 HandleAsync 函数的一些属性。我正在执行以下操作:
public async Task<TResponse> HandleAsync<TMessage, TResponse, TResponder>(TMessage message)
where TMessage : class
where TResponder : IRespondAsync<TMessage, TResponse>
{
using (var scope = this.BeginLifetimeScope(message))
{
var responder = scope.Resolve<TResponder>();
return await responder.Respond(message);
}
}
private ILifetimeScope BeginLifetimeScope<TMessage>(TMessage message)
{
var unwrapped = GetDomainContext(message);
var applicationPrincipalFactory = this.CreateApplicationPrincipalFactory(unwrapped);
var lifetime = this.container.BeginLifetimeScope(
r => r.RegisterInstance(applicationPrincipalFactory).As<IPrincipalFactory>());
return lifetime;
}
private ApplicationPrincipalFactory CreateApplicationPrincipalFactory(IDomainContext unwrapped)
{
var applicationPrincipalFactory =
new ApplicationPrincipalFactory(
unwrapped.Tenant,
unwrapped.ActingTenant,
unwrapped.Username);
return applicationPrincipalFactory;
}
根据我读过的所有内容,在 BeginLifetimeScope(r => 中定义依赖项应该覆盖父容器绑定,所以当我调用 resolve 时,它应该整齐地排列在一起。
但是,我得到一个例外:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Platform.Engine.Persistence.UnitOfWork' can be invoked with the available services and parameters: Cannot resolve parameter 'Platform.Engine.Security.IPrincipalFactory principalFactory' of constructor
除了这种方法,我没有在任何地方注册 IPrincipalFactory 。IUnitOfWork 在外部范围内定义如下:
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();
我还尝试在子容器中重新定义工作单元注册,以防通过在外部容器中注册而不是在生命周期中注册它是一个问题原因:
var lifetime = this.container.BeginLifetimeScope(
r => r.RegisterInstance(applicationPrincipalFactory).As<IPrincipalFactory>());
var overrides = new ContainerBuilder();
overrides.RegisterType<UnitOfWork>().As<IUnitOfWork>();
overrides.Update(lifetime.ComponentRegistry);
return lifetime;
我不确定我错过了什么......有什么想法或建议吗?