c# - 每个匹配生命周期范围的实例,默认?

标签 c# dependency-injection autofac lifetime-scoping

我想在 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/

相关文章:

c# - 关于枚举的简单问题

c# - WCF Rest 服务 - 获取对 HTTP 响应 header 的访问权限

c# - 为什么无法解析来自程序集的类型 CaSTLe Windsor

scala - 如何正确绑定(bind)同一服务的多个实现?

go - 在 Go Wire 注入(inject)中使用单例模式

dependency-injection - 如何让自托管与 IoC 配合进行 Web-Api 集成测试?

C# ASP.Net Core 与 Autofac 集成时面临的问题

c# - 在运行时更改 xamarin.forms 颜色

c# - 执行 native 代码时收到 SIGSEGV。这通常表示单声道运行时出现 fatal error

c# - 如何将 Fitnesse 与 Autofac/IOC 集成?