Autofac IComponentContext vs ILifetimeScope

8.1k views Asked by At

I was passing the IContainer in a service so I read that it is not good to pass this around but instead use it only to the root of the app and pass either IComponentContext or ILifetimeScope . So I am trying to understand which shall I use IComponentContext or ILifetimeScope. Dont understand the difference

1

There are 1 answers

1
Jeroen On BEST ANSWER

ILifetimeScope extends IComponentContext. It adds a few methods for beginning new lifetime scopes. If you need to create a new lifetime scope, then take a dependency on ILifetimeScope, otherwise I would suggest IComponentContext, so that you don't request more functionality than required.

Taking a dependency on either one is not an anti-pattern. There is always a boundary between your DI-aware code and the DI-unaware outside world. E.g. Windows has no knowledge about DI, but your code depends on Autofac. On this boundary you need to use ILifetimeScope or IComponentContext to bridge this gap. However if you can have your dependencies injected by Autofac instead of retrieved from a IComponentContext, then you should since this is the preferred option.