question

MNHHNGO-5213 avatar image
0 Votes"
MNHHNGO-5213 asked MNHHNGO-5213 action

Dependence injection

Recently, I work with ASP Boilerteample. It has classes to implement dependency injection such as ITransientDependency. When a class is inherited from the ITransientDependency class, it can be injected into the contructor without any configuration in the starup file. I want to do the same but don't know how. Please tell me what to do, is there a library to support or a document.

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

ArtemiyMorozUA avatar image
0 Votes"
ArtemiyMorozUA answered ArtemiyMorozUA edited

The IoC containers are used for dependency injection. There are many IoC containers, we use Ninject, as it is easy to use and understand. You can install the required package via NuGet. The package is called Ninject.MVC5.

After installing the package, we can already use Ninject in the project. For example, let's change the constructor of the controller as follows:


 using Ninject;
 //.....................
 public class HomeController : Controller
 {
     IRepository repo;
     public HomeController()
     {
         IKernel ninjectKernel = new StandardKernel();
         ninjectKernel.Bind<IRepository>().To<BookRepository>();
         repo = ninjectKernel.Get();
     
     }
     public ActionResult Index()
     {
         return View(repo.List());
     }
 }

Source: https://premius.net/blog/csharp-dotnet/136-using-ninject-in-c-asp-net-mvc5-projects.html


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered

A class implements an Interface. The class doesn't inherit from an Interface. An Interface can inherit from another Interface.

A class inherits from a class, like an abstract or a base class.

A class/object can be injected into another class/object, and the class that's being injected doesn't need an interface.

What 'start-up' are you talking about? One that is using an IoC?

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.