码迷,mamicode.com
首页 > 其他好文 > 详细

Autofac Property Injection and Method Injection

时间:2018-04-21 19:34:17      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:init   nal   ted   return   port   bsp   strong   red   initial   

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>() });

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);
  }); 

 

Autofac Property Injection and Method Injection

标签:init   nal   ted   return   port   bsp   strong   red   initial   

原文地址:https://www.cnblogs.com/lenmom/p/8902338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!