Search code examples
c#winformsdependency-injectionautofac

Should I Dispose instances that are not Owned?


I'm using Autofac in a project, and I'm trying to do it right. So I've been reading the documentation and found Owned<T>. It seems like it's the right relationship type to use when i want to dispose something by myself - e.g. a DbContext which is disposable.

So I changed all my injected factories Func<DbContext> to Func<Owned<DbContext>>.

The only thing is it feels a little dirty the Lazy<T> like behaviour and to put the Owned in the using and depending on a non framework type...

Is it wrong to not use Owned at all?

Is there an issue in disposing instances that are not owned by my class like this?

public class MyClass
{
    private readonly Func<DbContext> _dbcFactory;

    private MyClass(Func<DbContext> dbcFactory)
    {
        _dbcFactory = dbcFactory; // nullcheck etc;
    }
    private void TheMethodWhoUpdate(String newName) 
    {
        using(var dbc  = _dbcFactory())
        {
            var ent = dbc.Table.Single(x => x.id == 3);

            end.Name = newName;
            dbc.SaveChanges();
        }
    }
}

What I was able to imagine (because I can't find a clue on the docs) is that this could lead to some performance issue, because maybe autofac will track that created DbContext instance and try to dispose it again, losing some amount of time (probably very small)... But maybe I'm wrong, and I should stick to the guide.


Solution

  • Why not just use Func<DbContext> dbcFactory like shown in your code sample?

    You shouldn't do that, for two reasons.

    1. It is the container's job to dispose of it - so let it do its job.
    2. Secondly, if you register that DbContext as InstancePerLifetimeScope then multiple objects (involved in the same lifetime scope) will get the same instance of the DbContext - which is problematic if one of them disposes it out from under the other one.