Reputation: 67
ok, maybe I am missing something or worried to much...
I have a controller that generates my images. On a page it could have 100 or more images. For every image that is generated, the ImagingController is called. I use dependency injection and notice that for every image that is displayed, the dependent classes are constructed.
src="@Url.Action("Thumbnail", "Imaging")/id"
private readonly IDBAccess _dbaccess;
private readonly ILogger _logger;
private readonly ISettings _settings;
private readonly IStateManager _statemanager;
public ImagingController(IDBAccess dbaccess, ILogger logger, ISettings settings, IStateManager statemanager)
{
this._dbaccess = dbaccess;
this._logger = logger;
this._settings = settings;
this._statemanager = statemanager;
}
public ActionResult Thumbnail(int id)
{
...
return File((byte[])data, "image/jpeg");
}
So every of the above 4 dependent classes are constructed 100 times. This seems a bit too much overhead or am I wrong?
Upvotes: 3
Views: 92
Reputation: 233150
It's possible to optimize this using lifetime management. If one or more of the dependencies are thread-safe, there's no reason to create a new instance for every request. Instead, you can reuse the same instance for all 100 requests.
This is called the Singleton lifetime style (not to be confused with the Singleton design pattern).
You don't write if you use a DI Container, or wire dependencies up by hand, so for details on how to do this, I'll refer you to my book, which both explains how to do it manually, and how to configure lifetimes for 6 different DI Containers.
In addition, you may also find this article useful: http://blog.ploeh.dk/2011/03/04/Composeobjectgraphswithconfidence
Upvotes: 2