Search code examples
dependency-injectionautofacautofac-configuration

What is the correct way to share dependency instances in Autofac?


I have three classes, say, A, B and C, so that:

  • A depends on instances of B and C;
  • B depends on an instance of C;
  • Both A and B need to share the instance of C.

How can I configure the container to have the things correctly wired with a single call to Resolve<A>()?


Solution

  • That's what lifetime scopes are for. If you register something as single instance, it lives in the root lifetime scope and everything shares it. If you register as instance per lifetime scope, everything resolved in the same scope will share the same instance. Tons and tons of doc on this topic including examples.

    It can, of course, get way more complex. You can register a lambda with shared instances you manually create; you can use Owned<T> to create a tiny lifetime scope for an individual component... Again, tons of doc. I'd recommend doing some experiments on your own to get a good working knowledge.

    How you manage the scopes is up to you. You may get some ideas from this doc on handling per-request lifetime scopes. In a custom app with custom requirements, obviously there can't be "prescriptive guidance." Some people wrap units of work in lifetime scopes. Some people leave it to the integration packages and only use the provided request-level lifetime scope.

    • If you create a lifetime scope, it's up to you to clean it up. Autofac doesn't do that for you.
    • If an integration package creates the scope (e.g., web app integration creates the per-request scope) that package will clean it up. If you do it, you may run into trouble by disposing the scope too soon.