AutoFac 和 IDisposable
interface IMyResource { … } class MyResource : IMyResource, IDisposable { … }
var builder = new ContainerBuilder(); builder.RegisterType<MyResource>().As<IMyResource>(); using (var container = builder.Build()) { while (true) var r = container.Resolve<IMyResource>(); // Out of memory! }
上面这段代码会出现内存泄露的情况,Autofac生成出的实例没有获得释放(没有垃圾回收)
var builder = new ContainerBuilder(); builder.RegisterType<MyResource>().As<IMyResource>(); using (var container = builder.Build()) { while (true) var r = new MyResource(); // Fine, feed the GC }
而这段代码却完全正常。