首页 > AutoFac使用方法总结:Part I

AutoFac使用方法总结:Part I

utoFac是.net平台下的IOC容器产品,它可以管理类之间的复杂的依赖关系。在使用方面主要是register和resolve两类操作。 这篇文章用单元测试的形式列举了AutoFac的常用使用方法:

注册部分

使用RegisterType进行注册

[Fact]public void can_resolve_myclass(){var builder = new ContainerBuilder();builder.RegisterType();IContainer container = builder.Build();var myClass = container.Resolve();Assert.NotNull(myClass);}

 注册为接口

[Fact]public void register_as_interface(){var builder = new ContainerBuilder();builder.Register(c => new MyClass()).As();IContainer container = builder.Build();Assert.NotNull(container.Resolve());Assert.Throws(typeof (ComponentNotRegisteredException), () => container.Resolve());}

使用lambda表达式进行注册

[Fact]public void can_register_with_lambda(){var builder = new ContainerBuilder();builder.Register(c => new MyClass());IContainer container = builder.Build();var myClass = container.Resolve();Assert.NotNull(myClass);}

带构造参数的注册

    [Fact]public void register_with_parameter(){var builder = new ContainerBuilder();builder.Register(c => new MyParameter());builder.Register(c => new MyClass(c.Resolve()));IContainer container = builder.Build();Assert.NotNull(container.Resolve());}  

带属性赋值的注册

  [Fact]public void register_with_property(){var builder = new ContainerBuilder();builder.Register(c => new MyProperty());builder.Register(c => new MyClass(){Property = c.Resolve()});IContainer container = builder.Build();var myClass = container.Resolve();Assert.NotNull(myClass);Assert.NotNull(myClass.Property);}      

Autofac分离了类的创建和使用,这样可以根据输入参数(NamedParameter)动态的选择实现类。

  [Fact]public void select_an_implementer_based_on_parameter_value(){var builder = new ContainerBuilder();builder.Register((c, p) =>{var type = p.Named<string>("type");if (type == "test"){return new TestRepository();}else{return new DbRepository();}}).As();IContainer container = builder.Build();var repository = container.Resolve(new NamedParameter("type", "test"));Assert.Equal(typeof(TestRepository),repository.GetType());}

AufoFac也可以用一个实例来注册,比如用在单例模式情况下:

  [Fact]public void register_with_instance(){var builder = new ContainerBuilder();builder.RegisterInstance(MyInstance.Instance).ExternallyOwned();IContainer container = builder.Build();var myInstance1 = container.Resolve();var myInstance2 = container.Resolve();Assert.Equal(myInstance1,myInstance2);}

注册open generic类型

  [Fact]public void register_open_generic(){var builder = new ContainerBuilder();builder.RegisterGeneric(typeof (MyList<>));IContainer container = builder.Build();var myIntList = container.Resolveint>>();Assert.NotNull(myIntList);var myStringList = container.Resolvestring>>();Assert.NotNull(myStringList);}

对于同一个接口,后面注册的实现会覆盖之前的实现

  [Fact]public void register_order(){var containerBuilder = new ContainerBuilder();containerBuilder.RegisterType().As();containerBuilder.RegisterType().As();IContainer container = containerBuilder.Build();var repository = container.Resolve();Assert.Equal(typeof(TestRepository), repository.GetType());}

如果不想覆盖的话,可以用PreserveExistingDefaults,这样会保留原来注册的实现。

  [Fact]public void register_order_defaults(){var containerBuilder = new ContainerBuilder();containerBuilder.RegisterType().As();containerBuilder.RegisterType().As().PreserveExistingDefaults();IContainer container = containerBuilder.Build();var repository = container.Resolve();Assert.Equal(typeof (DbRepository), repository.GetType());}

可以用Name来区分不同的实现,代替As方法

  [Fact]public void register_with_name(){var containerBuilder = new ContainerBuilder();containerBuilder.RegisterType().Named("DB");containerBuilder.RegisterType().Named("Test");IContainer container = containerBuilder.Build();var dbRepository = container.ResolveNamed("DB");var testRepository = container.ResolveNamed("Test");Assert.Equal(typeof(DbRepository), dbRepository.GetType());Assert.Equal(typeof(TestRepository), testRepository.GetType());}

如果一个类有多个构造函数的话,可以在注册时候选择不同的构造函数

  [Fact]public void choose_constructors(){var builder = new ContainerBuilder();builder.RegisterType();builder.RegisterType().UsingConstructor(typeof (MyParameter));IContainer container = builder.Build();var myClass = container.Resolve();Assert.NotNull(myClass);}

AutoFac可以注册一个Assemble下所有的类,当然,也可以根据类型进行筛选

  [Fact]public void register_assembly(){var builder = new ContainerBuilder();builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();IContainer container = builder.Build();var repository = container.Resolve();Assert.NotNull(repository);}

 

转载于:https://www.cnblogs.com/wmlunge/archive/2013/03/28/2986729.html

更多相关:

  • //获取某一个cookie的值 const getCookie = key => {var k = key, dc = document.cookie;if (dc.length > 0) {var s = dc.indexOf(k + "=");if (s != -1) {s = s + k.length + 1;var e = d...

  • var SGheadMapPoints = {/*obj={ maxLng: minLng: maxLat: minLat: maxCount:最大人数 minCount:最小人数 total:点位数量 }*/get: function (obj) {var arr = [];obj.maxCount || (obj.maxCount...

  • //自动搜索指定的请柬 var alertTipText = "请柬找到了,就在这个网页里面,自己仔细看吧"; var delay = 1 * 1000;//1秒后循环下一页寻找 /*获取子DOM元素在父元素里面的索引位置(是第几个元素)*/ function getNodeListIndex(childNode) {return c...

  •  获取天气情况(不支持跨域) /*json原生获取*/ function getJSON() {var XML;var url = "http://wthrcdn.etouch.cn/weather_mini?city=杭州";if (window.XMLHttpRequest) {XML = new XMLHttpRequest(...

  • 菜鸟一枚,正在学习C++ Gui Qt4,整理很零碎,欢迎批评指正   1.窗口标题: QWidget *window = new QWidget; window->setWindowTitle("Enter Your Age"); **************************************** 关于标题...

  • 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 总体思路是: 比较两个链表头节点,较小的插入新链表指针之后,同时较小链表指针向后移动一位 实现如下: ListNode* mergeTwo...

  • 1.直接调用微软socket对象处理 static void Main(string[] args){try{IPAddress ip = new IPAddress(new byte[] { 127, 0, 0, 1 });//在3721端口新建一个TcpListener对象TcpListener listener = new...

  •   现在很多地方都会用到zookeeper, 用到它的地方就是为了实现分布式。用到的场景就是服务注册,比如一个集群服务器,需要知道哪些服务器在线,哪些服务器不在线。   ZK有一个功能,就是创建临时节点,当机器启动应用的时候就会连接到一个ZK节点,然后创建一个临时节点,那么通过获取监听该路径,并且获取该路径下的节点数量就知道有哪些服务...

  • 前台到后台java时data日期类型的转化 在实体类中用@DataTimeFormat,这样设置即使传过来是空的字符串也是可以转的,要和前面传过来的格式一致,如 @XmlElement(name="BeginDate") @DateTimeFormat(pattern="yyyy-MM-dd") private Date begin...