Search code examples
c#asp.net-coredependency-injectionclr

Proper handling of resources in asp.net core


I am trying to properly manage resources in asp.net core. Is it necessary to register every object I create inside the dependency injection container? If I register an object inside the dependency injection container what happens to objects I create inside that object? For example:

services.AddScoped<ISimpleObject1, SimpleObject1>();

public class SimpleObject1 : ISimpleObject1 {
        public const string Message = "Hello";
        public SimpleObject2 simpleObject2 = new SimpleObject2() { 
            Message2 = "Hello again"; 
        };
}

I'm fairly new to asp.net core and the CLR runtime. My thinking is that I only need to register classes that are IO intensive or Network resource heavy. I would like to write applications in the most performant manner possible so any advice or suggestions would be greatly appreciated.


Solution

  • In general Dependency Injection is not related to solving performance or resource issues. It is a design pattern for making your classes loosely coupled and separating concerns using the IoC principle.

    You do not have to register all dependencies as services. It depends on your application architecture. As a rule of thumb, I create and register services when there is a clear boundary between the responsibility of the classes.

    The object (SimpleObject2) you instantiate in the service you have registered will have the same life-time as your service (ISimpleObject1).

    See https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-lifetimes for more info on service life-time.