1

I was looking at a sample of how to setup Unity IoC with MVC, and noticed someone who recommended the approach of having the parameters of Func. I believe the advantage is this is kind of like lazy loading the service, if it never gets called it will never get executed and not consume any resources.

 private readonly Func<IUserService> _userService;

 public CourseController(Func<IUserService> userService)
 {
         this._userService = userService;
 }

Versus a parameter without a Func:

 private readonly IUserService _userService;

 public CourseController(IUserService userService)
 {
         this._userService = userService;
 }

Can someone explain to me the differences, is it really more effecient?

loyalflow
  • 14,275
  • 27
  • 107
  • 168
  • Why not `Lazy`? – Tim S. Nov 01 '13 at 20:02
  • @TimS.: probably because Unity 2 supported resolving `Func` automatically. Unity 3 now also supports `Lazy`. – Randy Levy Nov 01 '13 at 20:58
  • Object initialization is very fast if the object doesn't do much when it is initialized (as it should). Think of too much stuff in the constructor and many variable initializations. Use constructs like this when resources or performance indisputably suffer from eager service initialization. It _does_ add complexity and complexity always has a price in maintenance. Also, it side-tracks the IoC container when it comes to lifecycle management. With lazy initialization the action method is responsible for when and how to dispose the object, which may cause repetitive `usings` in the controller. – Gert Arnold Nov 01 '13 at 21:51

1 Answers1

1

One of the reasons to use Func<IUserService> instead of IUserService as dependency type is avoiding cyclic dependencies.

There is SO question Cyclic dependency with Castle Windsor IoC for NHibernate ISession I I've answered and suggested using of Func<ISession> instead of ISession.

If there is no cyclic dependency I prefer to use simply types.

If dependency is Func<IUserService> I am not sure if it is easy to have per-web-request instance of IUserService.

Community
  • 1
  • 1
Ilya Palkin
  • 14,687
  • 2
  • 23
  • 36