生命周期 AutoFac中的生命周期概念非常重要,AutoFac也提供了強大的生命周期管理的能力。 AutoFac定義了三種生命周期: Per Dependency為預設的生命周期,也被稱為’transient’或’factory’,其實就是每次請求都創建一個新的對象 Single Instance ...
生命周期
AutoFac中的生命周期概念非常重要,AutoFac也提供了強大的生命周期管理的能力。
AutoFac定義了三種生命周期:
Per Dependency
Single Instance
Per Lifetime Scope
Per Dependency為預設的生命周期,也被稱為’transient’或’factory’,其實就是每次請求都創建一個新的對象
1 [Fact]
2 public void per_dependency()
3 {
4 var builder = new ContainerBuilder();
5 builder.RegisterType<MyClass>().InstancePerDependency();
6 IContainer container = builder.Build();
7 var myClass1 = container.Resolve<MyClass>();
8 var myClass2 = container.Resolve<MyClass>();
9 Assert.NotEqual(myClass1,myClass2);
10 }
Single Instance也很好理解,就是每次都用同一個對象
1 [Fact]
2 public void single_instance()
3 {
4 var builder = new ContainerBuilder();
5 builder.RegisterType<MyClass>().SingleInstance();
6
7 IContainer container = builder.Build();
8 var myClass1 = container.Resolve<MyClass>();
9 var myClass2 = container.Resolve<MyClass>();
10
11 Assert.Equal(myClass1,myClass2);
12 }
Per Lifetime Scope,同一個Lifetime生成的對象是同一個實例
1 [Fact]
2 public void per_lifetime_scope()
3 {
4 var builder = new ContainerBuilder();
5 builder.RegisterType<MyClass>().InstancePerLifetimeScope();
6
7 IContainer container = builder.Build();
8 var myClass1 = container.Resolve<MyClass>();
9 var myClass2 = container.Resolve<MyClass>();
10
11 ILifetimeScope inner = container.BeginLifetimeScope();
12 var myClass3 = inner.Resolve<MyClass>();
13 var myClass4 = inner.Resolve<MyClass>();
14
15 Assert.Equal(myClass1,myClass2);
16 Assert.NotEqual(myClass2,myClass3);
17 Assert.Equal(myClass3,myClass4);
18 }
1 [Fact]
2 public void life_time_and_dispose()
3 {
4 var builder = new ContainerBuilder();
5 builder.RegisterType<Disposable>();
6
7 using (IContainer container = builder.Build())
8 {
9 var outInstance = container.Resolve<Disposable>(new NamedParameter("name", "out"));
10
11 using(var inner = container.BeginLifetimeScope())
12 {
13 var inInstance = container.Resolve<Disposable>(new NamedParameter("name", "in"));
14 }//inInstance dispose here
15 }//out dispose here
16 }
轉載鏈接:http://niuyi.github.io/blog/2012/04/06/autofact-by-unit-test3/