newbie here, sorry if this is an obvious question.
I’ve read from this page: http://code.google.com/p/autofac/wiki/NewInV2
In Autofac 1, weak references are held by the container. This makes sense if the objects being referenced use disposal to release GC/finalizer resources, but if the dispose method contains application logic then GC timing could introduce unexpected behaviour.
Autofac 2 holds normal references. To opt out of this behaviour and mange disposal manually, use the ExternallyOwned registration modifier.
Is that mean when I need to release an object that is resolved by Autofac to the GC, I cannot simply say:
a = null;
because Autofac holds a strong reference to the object. Instead, I should use Owned<>:
public class MyClass
{
public MyClass(Owned<A> a)
{
a.Value.Dosomething();
a.Dispose();
}
}
or use the ExternallyOwned registration modifier:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).ExternallyOwned();
later on, I should be able to use a = null to release the object to the GC.
Is that right?
Thanks!
By default, you don’t need to dispose anything – Autofac will automatically identify and dispose any
IDisposableinstances it created when their containing lifetime scope is disposed.You only need to use
Owned<T>orExternallyOwned()if you have a reason to manage the lifetime of the object manually. If you resolve anOwned<T>then you should callt.Dispose()yourself – the common usage pattern is to take a dependency on a factory delegate:If you register a type as
ExternallyOwned()then Autofac will not dispose of any resolved instance when the containing lifetime scope ends – it’s up to you to manage it.Take a look at Nicholas Blumhardt’s article on lifetimes for more information.