微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 每个匹配生命周期范围的实例,默认情况下?

我想在Autofac中为每个匹配的生命周期范围注册创建一个实例,但偶尔需要从全局容器(没有匹配的生命周期范围)请求实例.在没有匹配的生命周期范围的情况下,我想提供一个顶级实例而不是抛出异常.

这可能吗?

解决方法

我认为你最好通过引入新的生命周期选项来扩展Autofac.我使用了Autofac源并对其进行了一些修改
public static class RegistrationBuilderExtensions
{
    public static IRegistrationBuilder<TLimit,TActivatorData,TRegistrationStyle> InstancePerMatchingOrRootLifetimeScope<TLimit,TRegistrationStyle>(this IRegistrationBuilder<TLimit,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");

我自己没试过,但它应该有用.

原文地址:https://www.jb51.cc/csharp/91432.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐