Search code examples
c#dependency-injectioninversion-of-controlautofac

What does "Lifetime scopes are respected" means?


I'm reading the Implicit Relationship Types Section in Autofac official documentation, but i don't really understand this line.

Lifetime scopes are respected using this relationship type.

Who can help me explain that what on earth does 'respected' means?


Solution

  • 'respected' means Autofac will not override your registrations when you use Dynamic Instantiation.

    This is elaborated in the next 2 lines:

    If you register an object as InstancePerDependency() and call the Func<B> multiple times, you’ll get a new instance each time. However, if you register an object as SingleInstance() and call the Func<B> to resolve the object more than once, you will get the same object instance every time.


    Quoted from asker's comment:

    I understand the detailed explanations in the next 2 lines and i have wrote demos for that, but what's the connection to lifetime scope? Can I understand that lifetime scope is important, and will influence the instantiation?

    The connection to lifetime scope:

    When you dependency-inject an object, do I give you a new object or the singleton?

    Why lifetime scope is important and will influence instantiation:

    Does the object have instance attributes that should not be accessed elsewhere? If I give you a new object, should it be a singleton that exists for the rest of the application's lifetime?