Show / Hide Table of Contents
    • Updated: 3/22/2021
      • Andrei Mazulnitsyn
      • Anokhin Alexey

    Inversion of Control and Dependency Injection

    Inversion of Control and Dependency Injection are two related ways to break apart dependencies in your applications. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source. Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and sets properties. Martin Fowler has written a great description of Dependency Injection or Inversion of Control. I'm not going to duplicate his work, and you can find his article here. nopCommerce uses ASP.NET Core's built-in DI container, which is represented by the IServiceProvider interface. This container is responsible for mapping dependencies to specific types and for injecting dependencies into various objects. Once a service and an appropriate interface, which the service implements, are written you should register them in any class implementing the IDependencyRegistrar interface (Nop.Core.Infrastructure.DependencyManagement namespace). For example, all core nopCommerce services are registered in the DependencyRegistrar class located in the Nop.Web.Framework library.

        public class DependencyRegistrar : IDependencyRegistrar
        {
            public virtual void Register(IServiceCollection services, ITypeFinder typeFinder, NopConfig config)
            {
                    services.AddScoped<IWebHelper, WebHelper>();
                ...
            }
        }
    

    You can create as many dependency registrar classes as you need. Each class implementing IDependencyRegistrar interface has an Order property. It allows you to replace existing dependencies. To override nopCommerce dependencies, set the Order property to something greater than 0. nopCommerce orders dependency classes and runs them in ascending order. The higher the number the later your objects will be registered.

    • Improve this Doc
    Back to top Generated by DocFX