生命周期
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/