AutoFac使用方法總結 Part II

2022-02-07 06:48:28 字數 1282 閱讀 3365

autofac支援三種事件:onactivating,onactivated,onrelease。onactivating在註冊元件使用之 前會被呼叫,此時可以替換實現類或者進行一些其他的初始化工作,onactivated在例項化之後會被呼叫,onrelease在元件釋放之後會被調 用。

public

class

myevent : idisposable

public

myevent()

public

void

dispose()

}

public

void

test_event()

}}

此時的輸出為:

init

input

onactivated

dispose

onrelease

利用事件可以在構造物件之後呼叫物件的方法:

[fact]

public

void

call_method_when_init()

public

class

myclasswithmethod

public

void add(int

value)

}

迴圈依賴是個比較頭疼的問題,在autofac中很多迴圈依賴的場景不被支援:

public

class

classa

}public

class

classb

} [fact]

public

void

circular_dependencies_exception()

);builder.register(c => new classa(c.resolve()));

icontainer container =builder.build();

assert.throws(

typeof(dependencyresolutionexception), ()=>container.resolve());

}

可以部分的解決這種迴圈依賴的問題,前提是classa和classb的生命週期不能都是instanceperdependency

[fact]

public

void

circular_dependencies_ok()

AutoFac使用方法總結 Part I

autofac是.net平台下的ioc容器產品,它可以管理類之間的複雜的依賴關係。在使用方面主要是register和resolve兩類操作。這篇文章用單元測試的形式列舉了autofac的常用使用方法 使用registertype進行註冊 123 4567 8910 fact public void ...

AutoFac使用方法總結 Part II

autofac支援三種事件 onactivating,onactivated,onrelease。onactivating在註冊元件使用之前會被呼叫,此時可以替換實現類或者進行一些其他的初始化工作,onactivated在例項化之後會被呼叫,onrelease在元件釋放之後會被呼叫。123 4567...

AutoFac使用方法總結 Part III

autofac中的生命週期概念非常重要,autofac也提供了強大的生命週期管理的能力。autofac定義了三種生命週期 per dependency single instance per lifetime scope per dependency為預設的生命週期,也被稱為 transient 或...