在autofac中间件中检查构造函数参数

问题描述

我有以下情况:

public interface IService
{
    string Name { get; }
}

public class A : IService
{
    public string Name => "A";
}

public class B : IService
{
    public string Name => "B";
}

public class C
{
    public C(IService first,IService second)
    {
        Console.WriteLine(first.Name);
        Console.WriteLine(second.Name);
    }

    public C(IService single)
    {
        Console.WriteLine(single.Name);
    }
}

我正在使用 Autofac 作为我的DI容器。我想要的是让Autofac在具有相同服务类型的多个参数的情况下使用参数名称作为键来解析类C的依赖项,但仅在这种情况下 (示例中的single参数应正常解析)。

所以最终目标是要具有以下行为:

var builder = new ContainerBuilder();

builder.RegisterType<A>().Keyed<IService>("first");
builder.RegisterType<B>().Keyed<IService>("second");
builder.RegisterType<C>().AsSelf();

// possibly modify the container behavior here

C test = builder.Build().Resolve<C>();

// output:
// A
// B

在我的用例中,不能对每次注册中的行为进行硬编码(例如使用RegistrationExtensions.WithParameter)。 使用Autofac的middleware feature,我仅设法覆盖了所有参数的解析行为(无论构造函数中是否多次使用了参数类型)。 这是我到目前为止所拥有的:

public class ParameterNameAsKeyMiddleware : IResolveMiddleware
{
    public PipelinePhase Phase => PipelinePhase.ParameterSelection;

    public void Execute(ResolveRequestContext context,Action<ResolveRequestContext> next)
    {
        Parameter parameterKeyedByName = new ResolvedParameter(
            (p,i) => true,(p,i) =>
            {
                if (i.TryResolveKeyed(p.Name,p.ParameterType,out object instance))
                {
                    return instance;
                }
                return i.Resolve(p.ParameterType);
            }
        );
        var parameters = context.Parameters.Union(new[] { parameterKeyedByName });

        context.ChangeParameters(parameters);

        // Continue the resolve.
        next(context);
    }
}

并且我在构建容器之前添加了以下代码:

// Add custom middleware to every registration.
builder.ComponentRegistryBuilder.Registered += (sender,args) =>
{
    args.ComponentRegistration.PipelineBuilding += (sender2,pipeline) =>
    {
        pipeline.Use(new ParameterNameAsKeyMiddleware());
    };
};

任何帮助将不胜感激。


更新: 感谢Alistair的回答,这是一个可行的解决方案:

public class ParameterNameAsKeyMiddleware : IResolveMiddleware
{
    private static readonly ConcurrentDictionary<ConstructorInfo,IEnumerable<IGrouping<Type,ParameterInfo>>>
        duplicationCache = new ConcurrentDictionary<ConstructorInfo,ParameterInfo>>>();

    public PipelinePhase Phase => PipelinePhase.ParameterSelection;

    public void Execute(ResolveRequestContext context,Action<ResolveRequestContext> next)
    {
        Parameter parameterKeyedByName = new ResolvedParameter(
            DuplicatedServicePredicate,(pi,ctx) => ctx.ResolveKeyed(pi.Name,pi.ParameterType));
        var parameters = context.Parameters.Union(new[] { parameterKeyedByName });
        context.ChangeParameters(parameters);
        // Continue the resolve.
        next(context);

        #region Local functions,called only from the context of this method
        bool DuplicatedServicePredicate(ParameterInfo p,IComponentContext i)
        {
            var constructor = p.Member as ConstructorInfo;
            IEnumerable<IGrouping<Type,ParameterInfo>> duplications = GetDuplicateServices(constructor);
            bool isDuplicate = duplications.Any(g => g.Key == p.ParameterType);
            return isDuplicate;

            // gets groupings of multiple parameters implementing the same service (type).
            // if present,value is fetched from cache. otherwise value is reflected.
            IEnumerable<IGrouping<Type,ParameterInfo>> GetDuplicateServices(ConstructorInfo constructorInfo)
            {
                if (!duplicationCache.TryGetValue(
                        constructorInfo,out IEnumerable<IGrouping<Type,ParameterInfo>> duplicateServices))
                {
                    duplicateServices = constructorInfo.GetParameters()
                        .GroupBy(pi => pi.ParameterType)
                        .Where(g => g.Count() > 1);

                    duplicationCache.AddOrUpdate(
                        constructorInfo,duplicateServices,(x,y) => throw new InvalidOperationException("values should only be added"));
                }

                return duplicateServices;
            }
        }
        #endregion
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)