Search code examples
dependency-injection.net-corestatic-classes

.net core Dependency Injection vs rarely used static class


I am new to .net core and I am trying to port some old .dot net code.

Up to now I was using lots of static helper classes. One example is a class called 'ImageUtilities' that offered static methods like 'ResizeImage(..' or 'ResizeAndSavePNG(..' and so on. Or an other class is 'DateUtilities' with methods like 'GetCalendarWeek(..' or 'GetDaysBetween(..' This are just some examples, could be any static class.

Wher ever I needed one of those methods, i just called them. With .net core I could still do this but I would like to improve my code and try to follow best practice guidelines. This is why I changed this to use Dependency Injection.

Now in my startup class I have lots of code like this..

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IImageProcessor, ImageSharpProcessor>();
    services.AddSingleton<...
    services.AddSingleton<...
    services.AddSingleton<...
}

ImageShorpProcessor is a class that represents my 'old' class 'ImageUtilities' of the old .net net code. If a class now needs to call some of those methods I pass that class ImageSharpProcessor with Dependency injection in the constructor. This works very good and I hope this is the way to do it.

But in my application the ImageSharpProcessor class is rarely ever used as an example. And this is where my concerns start. 99% of the users of the website do not use the pages where this class is used in the code. The same applies to a lot of other helper methods which used to be static classes but now are methods that are used with Dependency Injection.

Question: Is this the proper way to use such util classes, that used to be static classes now with Dependency injection although they are rarely ever used in a website? Does the instantiation of all those classes like services.AddSingleton<... slow down the startup process of the Website? Or are they instantiatiated only at the point where they are used for the first time?

I hope you unterstand my concerns. Hopefully someone can give me some advise on that topic. It would be appreciated! Sorry for my english, best regards!


Solution

  • Does the instantiation of all those classes like services.AddSingleton<... slow down the startup process of the Website?

    NO.

    Registering them with the DI container does not affect performance, provided that they are simply registered and not initialized before adding them to the container.

    Or are they instantiated only at the point where they are used for the first time?

    Those singletons will only be initialized when or if the page/class that needs them are initialize


    The fact that they are not used frequently is of no consequence. The fact that they are used at all in the system for it to perform its function is the reason why tried and practiced design principles should be applied.