0

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>()?

vines
  • 5,160
  • 1
  • 27
  • 49

1 Answers1

3

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.
Travis Illig
  • 23,195
  • 2
  • 62
  • 85
  • Yep, I've seen these. Actually, what I couldn't figure out from them is: how do I manage the scopes themselves now? Do I store them in my objects? It feels awkward to... – vines May 21 '19 at 15:25
  • That should probably have been part of your question, then; this is starting to get into a different question. I've updated my answer, however, the answer for the provided question has been given so if you need more help, I'd recommend accepting this as the answer and then creating a new question with more detailed information on what you're trying to achieve. – Travis Illig May 21 '19 at 16:12