0

Hopefully this isn't a duplicate question. I've been trying to find a good solution (maybe there just isn't one for .NET Framework console applications) for implementing Autofac without the service locator anti-pattern and still using lifetime scopes to avoid possible leaks.

I read the getting started guide: Autofac Getting Started

And found:

The container itself is a lifetime scope, and you can technically just resolve things right from the container. It is not recommended to resolve from the container directly, however.

I also found multiple answers about implementing Autofac in a console app where it seems the recommended approach to avoid service locator is to make two classes. The static composition root where all dependencies are registered and the container is used to resolve the second Application Runner class.

Generally Accepted Answer on SO

This approach avoids service locator but you resolve all dependencies from the root container which the Autofac docs say you shouldn't do. They say you can avoid this by using one of their Integration Libraries. But none of those are for .NET Framework.

Is there any good way in a .NET Framework console application to avoid service locator but still use child lifetime scopes to manage dependency disposal?

nitewulf50
  • 530
  • 1
  • 4
  • 17
  • Posting code would help. – Tanveer Badar Aug 17 '22 at 15:37
  • 1
    The reason you don't resolve from the container is because in a request/response semantic you won't be able to dispose request objects because they'll be held by the container. It's a memory issue. In a console app there's no request/response (unless the console app is generic hosting for a service, but generally speaking...) so container is fine. The app doesn't live long and the container is disposed after the app runs. No leak. – Travis Illig Aug 17 '22 at 23:28
  • Thank you @TravisIllig for the response. I get it. For 99% of console apps the "Generally Accepted Answer" is perfect. – nitewulf50 Aug 25 '22 at 15:27

0 Answers0