Autofac - 方法注入

來源:互聯網
上載者:User

標籤:注入   png   ges   interface   var   結束   tin   turn   console   

方法注入, 其實就是在註冊類的時候, 把這個方法也註冊進去. 那麼在產生執行個體的時候, 會自動調用這個方法.

其實現的方法, 有兩種.

準備工作:

public interface IAnimal{    void Say();}public class Dog : IAnimal{    public string Name { get; set; }    public void Say()    {        Console.WriteLine("汪汪汪!");        if (!string.IsNullOrEmpty(Name))        {            Console.WriteLine("此汪名叫 " + Name);        }    }}public class Person {    public void Say(IAnimal adopt)    {        Console.WriteLine("我領養了一隻小動物");        adopt.Say();    }}

1. 方法一 - 常規方法

var builder = new ContainerBuilder();builder.RegisterType<Dog>().As<IAnimal>();builder.Register(c =>{    var result = new Person();    result.Say(c.Resolve<IAnimal>());    return result;});var container = builder.Build();var person = container.Resolve<Person>();

執行時機 : 首先執行的, 肯定是Person的建構函式, 然後回去調用這個方法, 調用過程中, 發現了IAnimal 參數, 然後去載入參數的建構函式, 再回來執行Say方法, 一直到Say結束.

2. 方法二 - OnActivating/OnActivated

var builder = new ContainerBuilder();builder.RegisterType<Dog>().As<IAnimal>();builder.RegisterType<Person>().OnActivated(e => e.Instance.Say(e.Context.Resolve<IAnimal>()));var container = builder.Build();var person = container.Resolve<Person>();

結果是一樣的, 就不貼了.

上一次的例子, 我用的是 OnActivating, 這裡用後面一個好了, 實際過程中, OnActivating方法在OnActivated前面執行. 但是他們都是在建構函式後面執行.

Autofac - 方法注入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.