15

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

pantonis
  • 5,601
  • 12
  • 58
  • 115
  • You should not depend on `IComponentContext` or `ILifetimeScope` or `IComponent` if you need such components, you are using dependency injection as a service locator which is an anti-pattern. You can read http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/ for more information – Cyril Durand May 29 '17 at 12:07
  • 1
    Thanks for your reply. I know it is an anti-pattern but for now I cant avoid it.I only need this to fire up Controllers. From that point and on I use Autofac in the constructor of my classes. So can anyone explain please the difference? – pantonis May 31 '17 at 05:25
  • Anyone knows how to use it? – pantonis Jun 19 '17 at 13:53
  • Could you edit your post to explain why you need it ? I can't understand why you can't simply depends on the component instead of the lifetimescope – Cyril Durand Jun 19 '17 at 14:12
  • 8
    @CyriilDurand Listen I understand and respect what you said that is not correct to use. And I know why. But you have to understand that it is my choice to use it. The question here is not whether I should use it or not but trying to understand the difference. Thanks – pantonis Jun 19 '17 at 14:25
  • 1
    @CyrilDurand Depending on `IComponentContext` or `ILifetimeScope` is totally fine in certain cases. https://blog.ploeh.dk/2011/09/19/MessageDispatchingwithoutServiceLocation/ – Myk Nov 27 '19 at 22:58

1 Answers1

32

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.

Jeroen
  • 1,212
  • 10
  • 24