在我当前的项目中,我使用了很多“责任链”模式。
但是,我发现通过依赖项注入配置链有点尴尬。
给出此模型:
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) { /*...*/}
}
我的启动变为:
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>())
);
}
如何更清晰地配置我的责任链?
答案 0 :(得分:0)
我找到了一个简单的解决方案,因为找不到任何可以满足我要求的东西。只要GetRequiredService
可以解析链中所有处理程序的所有构造函数依赖关系,就可以正常工作。
我的启动课程变为:
public void ConfigureServices(IServiceCollection services)
{
services.Chain<IChainOfResponsibility>()
.Add<HandlerOne>()
.Add<HandlerTwo>()
.Configure();
}
执行魔术的代码:
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);
if (!_interfaceType.IsAssignableFrom(type))
throw new ArgumentException($"{type.Name} type is not an implementation of {_interfaceType.Name}", nameof(type));
_types.Add(type);
return this;
}
public void Configure()
{
if (_types.Count == 0)
throw new InvalidOperationException($"No implementation defined for {_interfaceType.Name}");
bool first = true;
foreach (var type in _types)
{
ConfigureType(type, first);
first = false;
}
}
private void ConfigureType(Type currentType, bool first)
{
var nextType = _types.SkipWhile(x => x != currentType).SkipWhile(x => x == currentType).FirstOrDefault();
var ctor = currentType.GetConstructors().OrderByDescending(x => x.GetParameters().Count()).First();
var parameter = Expression.Parameter(typeof(IServiceProvider), "x");
var ctorParameters = ctor.GetParameters().Select(x =>
{
if (_interfaceType.IsAssignableFrom(x.ParameterType))
{
if (nextType == null)
return Expression.Constant(null, _interfaceType);
else
return Expression.Call(typeof(ServiceProviderServiceExtensions), "GetRequiredService", new Type[] { nextType }, parameter);
}
return (Expression)Expression.Call(typeof(ServiceProviderServiceExtensions), "GetRequiredService", new Type[] { x.ParameterType }, parameter);
});
var body = Expression.New(ctor, ctorParameters.ToArray());
var resolveType= first ? _interfaceType : currentType;
var expressionType = Expression.GetFuncType(typeof(IServiceProvider), resolveType);
var expression = Expression.Lambda(expressionType, body, parameter);
Func<IServiceProvider, object> x = (Func<IServiceProvider, object>)expression.Compile();
_services.AddTransient(resolveType, x);
}
}
}
PS .:我正在回答自己的问题以供将来参考(我自己,并希望是其他人),但我希望对此有一些反馈。
答案 1 :(得分:0)
适用于最简单的依赖关系链的快速解决方案。
public static IServiceCollection AddChained<TService>(this IServiceCollection services, params Type[] implementationTypes)
{
if (implementationTypes.Length == 0)
{
throw new ArgumentException("Pass at least one implementation type", nameof(implementationTypes));
}
foreach(Type type in implementationTypes)
{
services.AddScoped(type);
}
int order = 0;
services.AddTransient(typeof(TService), provider =>
{
//starts again
if (order > implementationTypes.Length - 1)
{
order = 0;
}
Type type = implementationTypes[order];
order++;
return provider.GetService(type);
});
return services;
}
然后
services.AddChained<IService>(typeof(SomeTypeWithIService), typeof(SomeType));