c# - 如何在责任链中注入(inject)下一个处理程序的依赖?

标签 c# asp.net-core dependency-injection decorator chain-of-responsibility

在我当前的项目中,我使用了很多责任链模式。

但是,我发现通过依赖注入(inject)来配置链有点尴尬。

给定这个模型:

public interface IChainOfResponsibility 
{
    IChainOfResponsibility Next { get; }
    void Handle(Foo foo);
}

public class HandlerOne : IChainOfResponsibility 
{
    private DbContext _dbContext;

    public HandlerOne(IChainOfResponsibility next, DbContext dbContext)
    {
        Next = next;
        _dbContext = dbContext;
    }

    public IChainOfResponsibility Next { get; }

    public void Handle(Foo foo) { /*...*/}
}

public class HandlerTwo : IChainOfResponsibility 
{
    private DbContext _dbContext;

    public HandlerTwo(IChainOfResponsibility next, DbContext dbContext)
    {
        Next = next;
        _dbContext = dbContext;
    }

    public IChainOfResponsibility Next { get; }

    public void Handle(Foo foo) { /*...*/}
}

我的 Startup 变成了:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IChainOfResponsibility>(x => 
        new HandlerOne(x.GetRequiredService<HandlerTwo>(), x.GetRequiredService<DbContext>())
    );

    services.AddTransient(x => 
        new HandlerTwo(null, x.GetRequiredService<DbContext>())
    );
}

如何更清晰地配置我的责任链?

最佳答案

我找到了一个简单的解决方案,因为我找不到任何能满足我要求的东西。它工作正常,因为它使用 IServiceProvider.GetRequiredService 来解析链中所有处理程序的所有构造函数依赖性。

我的启动类变成了:

public void ConfigureServices(IServiceCollection services)
{
    services.Chain<IChainOfResponsibility>()
        .Add<HandlerOne>()
        .Add<HandlerTwo>()
        .Configure();
}

我正在做的是使用 Expression 在问题中动态生成 lambda。然后在 IServiceCollection.AddTransient 中进行编译和注册。

因为它生成编译代码,在运行时它应该和问题注册一样快。

这是神奇的代码:

public static class ChainConfigurator
{
    public static IChainConfigurator<T> Chain<T>(this IServiceCollection services) where T : class
    {
        return new ChainConfiguratorImpl<T>(services);
    }

    public interface IChainConfigurator<T>
    {
        IChainConfigurator<T> Add<TImplementation>() where TImplementation : T;
        void Configure();
    }

    private class ChainConfiguratorImpl<T> : IChainConfigurator<T> where T : class
    {
        private readonly IServiceCollection _services;
        private List<Type> _types;
        private Type _interfaceType;

        public ChainConfiguratorImpl(IServiceCollection services)
        {
            _services = services;
            _types = new List<Type>();
            _interfaceType = typeof(T);
        }

        public IChainConfigurator<T> Add<TImplementation>() where TImplementation : T
        {
            var type = typeof(TImplementation);

            _types.Add(type);

            return this;
        }

        public void Configure()
        {
            if (_types.Count == 0)
                throw new InvalidOperationException($"No implementation defined for {_interfaceType.Name}");

            foreach (var type in _types)
            {
                ConfigureType(type);
            }
        }

        private void ConfigureType(Type currentType)
        {
            // gets the next type, as that will be injected in the current type
            var nextType = _types.SkipWhile(x => x != currentType).SkipWhile(x => x == currentType).FirstOrDefault();

            // Makes a parameter expression, that is the IServiceProvider x 
            var parameter = Expression.Parameter(typeof(IServiceProvider), "x");

            // get constructor with highest number of parameters. Ideally, there should be only 1 constructor, but better be safe.
            var ctor = currentType.GetConstructors().OrderByDescending(x => x.GetParameters().Count()).First();

            // for each parameter in the constructor
            var ctorParameters = ctor.GetParameters().Select(p =>
            {
                // check if it implements the interface. That's how we find which parameter to inject the next handler.
                if (_interfaceType.IsAssignableFrom(p.ParameterType))
                {
                    if (nextType is null)
                    {
                        // if there's no next type, current type is the last in the chain, so it just receives null
                        return Expression.Constant(null, _interfaceType);
                    }
                    else
                    {
                        // if there is, then we call IServiceProvider.GetRequiredService to resolve next type for us
                        return Expression.Call(typeof(ServiceProviderServiceExtensions), "GetRequiredService", new Type[] { nextType }, parameter);
                    }
                }
                
                // this is a parameter we don't care about, so we just ask GetRequiredService to resolve it for us 
                return (Expression)Expression.Call(typeof(ServiceProviderServiceExtensions), "GetRequiredService", new Type[] { p.ParameterType }, parameter);
            });

            // cool, we have all of our constructors parameters set, so we build a "new" expression to invoke it.
            var body = Expression.New(ctor, ctorParameters.ToArray());
            
            // if current type is the first in our list, then we register it by the interface, otherwise by the concrete type
            var first = _types[0] == currentType;
            var resolveType = first ? _interfaceType : currentType;
            var expressionType = Expression.GetFuncType(typeof(IServiceProvider), resolveType);

            // finally, we can build our expression
            var expression = Expression.Lambda(expressionType, body, parameter);

            // compile it
            var compiledExpression = (Func<IServiceProvider, object>)expression.Compile();

            // and register it in the services collection as transient
            _services.AddTransient(resolveType, compiledExpression );
        }
    }
}

PS.:我正在回答我自己的问题以供将来引用(我自己和其他人),但我希望得到一些反馈。

关于c# - 如何在责任链中注入(inject)下一个处理程序的依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55476378/

相关文章:

asp.net-mvc - 如何在 .net core 项目中安装 jquery?

asp.net-core - 在 Asp.Net Core Web Api 中验证 B2C JWT token

Asp.Net 5(核心)RC1 : How to log to file (rolling file logging) [DNX Core 5 compatible solution]?

azure - .NET Azure Functions 中的依赖项注入(inject) - Azure Cosmos DB 客户端

java - Android - Dagger 不生成 DaggerModelComponent.create()

c# - .wsuo 文件是什么?

c# - 添加到选定文本操作菜单

c# - 来自 Gridview 中 UserControl 的事件未被触发

c# - 如何在 XAML 中使用条件打印文本 block ?

javascript - 资源解释为脚本,但在注入(inject) angular-route.map 时以 MIME 类型 text/html 传输