使用下面的PipelineX类,有任何方法可以解决应用于pipline的过滤器,而无需注入autofac容器并调用_container.Resolve();.
Using this PipelineX class below, is there any way to resolve the filters applied to the pipline without injecting the autofac container and calling _container.Resolve();
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用作服务定位器,您可以在其中注册自己的工厂方法,在这种情况下:
To avoid the usage of Autofac as a service locator you can register your own factory method into it, in this case:
builder.Register<Func<Type, object>>((c, p) => { var context = c.Resolve<IComponentContext>(); return type => context.Resolve(type); });并像下面这样在您的PipelineX类中使用它:
and use that in your PipelineX class like this:
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容器的硬引用,它仍使用抽象对象工厂,该工厂本身不足以说明自身,应由自定义过滤器工厂或选择器实现代替.
Consider: This only removes the hard reference to the Autofac container, it's still using an abstract object factory which is not self explanatory enough and should be replaced by a custom filter factory or selector implementation.
更多推荐
使用autofac在方法内部解析类的实例
发布评论