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.
CodePudding user response:
I order to register an object with the dependency service, you need to specify the type that it implements/represents in the dependency service.
Your code probably doesn't work as it is because the class SimpleObject1
isn't inheriting/implementing ISimpleObject1
.
That being said, you're passing two types here. The type it represents, (ISimpleObject1
), and the implementation type (SimpleObject1
). The dependency service won't look through objects to register them because it doesn't know what type they represent. This might also be a performance thing. Reflection is very expansive.
My suggestion would be to register every service you need with services.Add*()
methods.
CodePudding user response:
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://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-lifetimes for more info on service life-time.