Is this dependency injection if I change the below code
class Needer
{
Needed obj;
AnotherNeeded obj2;
public Needer()
{
obj = new Neede();
obj2 = new AnotherNeede();
}
}
To this code
class Needer
{
Needed obj;
AnotherNeeded obj2;
public Needer(Needed param1, AnotherNeeded param2)
{
obj = param1;
obj2 = param2;
}
}
The IServiceProvider is responsible for resolving instances of types at runtime, as required by the application. These instances can be injected into other services resolved from the same dependency injection container. The ServiceProvider ensures that resolved services live for the expected lifetime.
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
DependencyInjection disposes registered services automatically. It's just the question when the dispose takes place. Automatic dispose of transient and scoped services happen at the end of a scope. With ASP.NET Core applications, scopes are created with every HTTP request – after the request, services are disposed.
Robert C. Martin described Dependency Injecton in his SOLID design proposal. It basically states that:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Notice a word being used a lot in that description? "Abstraction".
You get part of the problem right in your second example, you no longer manually instantiate instances of the class, you instead pass them through the constructor. This leads into a new potential problem though, what if you need a different implementation of some class (e.g a "mock" and "real" services). If your constructor took the abstractions instead of the concretes you could change the implementations in your IoC configuration.
Any sort of service or functional class should typically have an abstraction behind it. This allows your code to be more flexible, extendable and easier to maintain. So to make your second example use true dependency injection:
class Needer
{
public INeeded obj { get; set; }
public IAnotherNeeded obj2 { get; set; }
public Needer(INeeded param1, IAnotherNeeded param2)
{
obj = param1;
obj2 = param2;
}
}
Now you can have all sorts of implementations:
public class MockNeeded : INeeded
public class ApiNeeded : INeeded
etc, etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With