Resolve instances in static functions using LightInject

800 Views Asked by At

I'm using LightInject in an ASP MVC project. The initialization code is more or less the same as on: http://www.lightinject.net/#mvc

My question is how to resolve instances in static functions, for example an HTML helper:

public static string MyHtmlExtension(this HtmlHelper h)
{
  var myService = new MyService(); // <- get this from container instead of creating new object
  return myService.DoSomething(h);
}

Can I make the ServiceContainer in the MvcApplication class static or is that a bad practice?

1

There are 1 best solutions below

2
On BEST ANSWER

You could make the container a singleton (static) since in most cases there will be only one container instance per application domain. That being said I would not recommend accessing the container from within an extension method. What you are basically doing here is the service locator pattern which is considered an anti-pattern. Try to organize your code in such a way that you only reference the container in the composition root (application startup). So in this case you should either consider making an extension method without the container or you could inject the HtmlHelper into whatever class that needs it.

Regards Bernhard Richter (Author of LightInject)