每个匹配一生范围的

每个匹配一生范围的

本文介绍了每个匹配一生范围的,具有默认实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每个有生命周期相匹配的实例在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 IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> InstancePerMatchingOrRootLifetimeScope(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.

这篇关于每个匹配一生范围的,具有默认实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 11:04