Dependence injection

MẠNH HÙNG ĐÀO 1 Reputation point
2021-04-24T04:55:17.233+00:00

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.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,218 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Artemiy Moroz 271 Reputation points
    2021-04-24T14:14:46.667+00:00

    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

    0 comments No comments

  2. Duane Arnold 3,211 Reputation points
    2021-04-24T15:53:24.993+00:00

    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?

    0 comments No comments