Strong reference of Autofac 2
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 IDisposable
instances it created when their containing lifetime scope is disposed.
You only need to use Owned<T>
or ExternallyOwned()
if you have a reason to manage the lifetime of the object manually. If you resolve an Owned<T>
then you should call t.Dispose()
yourself - the common usage pattern is to take a dependency on a factory delegate:
public class MyClass
{
private Func<Owned<User>> myDisposableFactory;
public MyClass(Func<Owned<User>> myDisposableFactory)
{
this.myDisposableFactory = myDisposableFactory;
}
public void DoSomething()
{
using (var disposable = this.myDisposableFactory())
{
// ...
disposable.Dispose();
}
}
}
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.
精彩评论