Autofac property injection

https://autofaccn.readthedocs.io/en/latest/register/prop-method-injection.html

Property and Method Injection

While constructor parameter injection is the preferred method of passing values to a component being constructed, you can also use property or method injection to provide values.

Property injection uses writeable properties rather than constructor parameters to perform injection.

Method injection sets dependencies by calling a method.

 

Property Injection

If the component is a lambda expression component, use an object initializer:

builder.Register(c => new A { B = c.Resolve<B>() }); B作为A的属性 

To support circular dependencies, use an activated event handler:

builder.Register(c => new A()).OnActivated(e => e.Instance.B = e.Context.Resolve<B>()); 

If the component is a reflection component 构造函数注入的, use the PropertiesAutowired() modifier to inject properties:    

builder.RegisterType<A>().PropertiesAutowired(); 

If you have one specific property and value to wire up, you can use the WithProperty() modifier:

builder.RegisterType<A>().WithProperty("PropertyName", propertyValue); 

Method Injection

The simplest way to call a method to set a value on a component is to use a lambda expression component and handle the method call right in the activator:

builder.Register(c => { var result = new MyObjectType(); var dep = c.Resolve<TheDependency>(); result.SetTheDependency(dep); return result; }); 

If you can’t use a registration lambda, you can add an activating event handler:

builder
  .Register<MyObjectType>() .OnActivating(e => { var dep = e.Context.Resolve<TheDependency>(); e.Instance.SetTheDependency(dep); }); 

 

扩展阅读

https://www.cnblogs.com/jiagoushi/p/4084145.html

http://www.cnblogs.com/artech/p/asp-net-core-di-di.html 

 

转载于:https://www.cnblogs.com/chucklu/p/10331015.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值