问题描述
我想在 Autofac 中为每个匹配的生命周期范围注册一个实例,但偶尔需要从全局容器(没有匹配的生命周期范围)请求一个实例.在不存在匹配的生命周期范围的场景中,我想给出一个顶级实例而不是抛出异常.
I'd like to have an instance per matching lifetime scoped registration in Autofac, but occasionally need to request an instance from a global container (where there is no matching lifetime scope). In scenarios where no matching lifetime scope exists, I want to give a top-level instance instead of throwing an exception.
这可能吗?
推荐答案
我认为您最好通过引入新的生命周期选项来扩展 Autofac.我采用了 Autofac 源并对其进行了一些修改:
I think you'd better extend Autofac by introducing a new lifetime option. I took the Autofac sources and modified them a bit:
public static class RegistrationBuilderExtensions
{
public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> InstancePerMatchingOrRootLifetimeScope<TLimit, TActivatorData, TRegistrationStyle>(this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> builder, params object[] lifetimeScopeTag)
{
if (lifetimeScopeTag == null) throw new ArgumentNullException("lifetimeScopeTag");
builder.RegistrationData.Sharing = InstanceSharing.Shared;
builder.RegistrationData.Lifetime = new MatchingScopeOrRootLifetime(lifetimeScopeTag);
return builder;
}
}
public class MatchingScopeOrRootLifetime: IComponentLifetime
{
readonly object[] _tagsToMatch;
public MatchingScopeOrRootLifetime(params object[] lifetimeScopeTagsToMatch)
{
if (lifetimeScopeTagsToMatch == null) throw new ArgumentNullException("lifetimeScopeTagsToMatch");
_tagsToMatch = lifetimeScopeTagsToMatch;
}
public ISharingLifetimeScope FindScope(ISharingLifetimeScope mostNestedVisibleScope)
{
if (mostNestedVisibleScope == null) throw new ArgumentNullException("mostNestedVisibleScope");
var next = mostNestedVisibleScope;
while (next != null)
{
if (_tagsToMatch.Contains(next.Tag))
return next;
next = next.ParentLifetimeScope;
}
return mostNestedVisibleScope.RootLifetimeScope;
}
}
只需将这些类添加到您的项目并将您的组件注册为:
Just add these classes to your project and register you component as:
builder.RegisterType<A>.InstancePerMatchingOrRootLifetimeScope("TAG");
我自己没试过,但应该可以.
I haven't tried it myself, but it should work.
这篇关于每个匹配的生命周期范围的实例,默认情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!