使用autofac在方法内部解析类的实例

编程入门 行业动态 更新时间:2024-10-27 18:32:29
本文介绍了使用autofac在方法内部解析类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用下面的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在方法内部解析类的实例

本文发布于:2023-11-05 21:13:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561875.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   方法   autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!