Eugene Strizhok
Eugene Strizhok

Reputation: 1188

How to run logic before lifetime scope is ended in autofac?

I know there is the OnRelease method when you register a component, there is also CurrentScopeEnding event on ILifetimeScope, but strangely enough code in both these extension points is executed after you no longer allowed to resolve anything using the lifetime scope in question. You'll get ObjectDisposedException if you try. But I need to! What can I do?

Upvotes: 0

Views: 483

Answers (2)

David L
David L

Reputation: 11

I know this thread is hella old but it's still open so I consider it free game. Plus I just solved this on my own so I thought I'd answer it since it was high in my google results. Might help some others out.

Here's what I did to log the lifetimes of ILifetimeScope instances:


class LifetimeLogger : IStartable
{
    readonly ILifetimeScope _lifetimeScope;

    public LifetimeLogger(ILifetimeScope lifetimeScope)
    {
        _lifetimeScope = lifetimeScope;
        //_lifetimeScope = scope;
    }

    public void Start()
    {
        initLifetimeScope(_lifetimeScope);
    }

    static void initLifetimeScope(ILifetimeScope lifetimeScope)
    {
        //lifetimeScope.
        lifetimeScope.ChildLifetimeScopeBeginning += (sender, args) =>
        {
            log("Begging lifetime scope (tag {0})", args.LifetimeScope.Tag);
            initLifetimeScope(args.LifetimeScope);
        };

        lifetimeScope.CurrentScopeEnding += (sender, args) => log("Ending lifetime scope ({0})", args.LifetimeScope.Tag);
    }
}

You could use something like and you'll get to execute logic at the beginning and end of every child lifetime scope.

Upvotes: 1

Dmitry Naumov
Dmitry Naumov

Reputation: 1

It's a bit strange to resolve anything from the scope when you current lifetime scope is disposing. Why do you need it? Try to resolve "the thing you need" from root scope.

Upvotes: 0

Related Questions