使用下面的这个PipelineX类,有没有办法解决应用于pipline的过滤器而不注入autofac容器并调用_container.Resolve(); public class PipelineXT : FilterBaseT, IPipelineXT{ private readonly IContainer _container; public Pi
public class PipelineX<T> : FilterBase<T>, IPipelineX<T> { private readonly IContainer _container; public PipelineX(IContainer container) { _container = container; } protected override T Process(T input) { return input; } public PipelineX<T> FilterBy<X>() { var filter = _container.Resolve(typeof(X)) as IFilter<T>; Register(filter); return this; } }为了避免将Autofac用作服务定位器,您可以在其中注册自己的工厂方法,在这种情况下:
builder.Register<Func<Type, object>>((c, p) => { var context = c.Resolve<IComponentContext>(); return type => context.Resolve(type); });
并在您的PipelineX类中使用它,如下所示:
private readonly Func<Type, object> filterFactory; public PipelineX(Func<Type, object> filterFactory) { this.filterFactory = filterFactory; } protected override T Process(T input) { return input; } public PipelineX<T> FilterBy<X>() { var filter = this.filterFactory(typeof(X)) as IFilter<T>; Register(filter); return this; }
考虑:这只删除了对Autofac容器的硬引用,它仍然使用一个抽象对象工厂,该工厂不够自我解释,应该由自定义过滤器工厂或选择器实现替换.