我想在Autofac中每个匹配的生存期范围内的注册都有一个实例,但是偶尔需要从全局容器(没有匹配的生存期范围)中请求一个实例。在不存在匹配的生存期范围的情况下,我想提供一个顶级实例,而不是引发异常。

这可能吗?

最佳答案

我认为您最好通过引入新的生命周期选项来扩展Autofac。我采用了Autofac的源代码并对其进行了一些修改:

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;
    }
}

只需将这些类添加到您的项目中,然后将组件注册为:
builder.RegisterType<A>.InstancePerMatchingOrRootLifetimeScope("TAG");

我自己还没有尝试过,但是应该可以。

关于c# - 每个匹配生存期范围的实例,默认设置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14672541/

10-12 00:27