UrbanPro
true

Learn .Net Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Inversion of Control

Ranjan P.
25/09/2017 0 0

Problem

You have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB. Figure 1 illustrates this.

Ff921087.35d9aa8f-1568-431b-9d7f-db477ae067dc(en-us,PandP.10).png

Figure 1 
ClassA has dependencies on ServiceA and ServiceB

This situation has the following problems:

  • To replace or update the dependencies, you need to change your classes' source code.
  • The concrete implementations of the dependencies have to be available at compile time.
  • Your classes are difficult to test in isolation because they have direct references to dependencies. This means that these dependencies cannot be replaced with stubs or mocks.
  • Your classes contain repetitive code for creating, locating, and managing their dependencies.

Forces

Any of the following conditions justifies using the solution described in this pattern:

  • You want to decouple your classes from their dependencies so that the dependencies can be replaced or updated with minimal or no changes to your classes' source code.
  • You want to write classes that depend on classes whose concrete implementations are not known at compile time.
  • You want to test your classes in isolation, without using the dependencies.
  • You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.

Solution

Delegate the function of selecting a concrete implementation type for the classes' dependencies to an external component or source.

Implementation Details

The Inversion of Control pattern can be implemented in several ways. The Dependency Injection pattern and the Service Locator pattern are specialized versions of this pattern that delineate different implementations. Figure 2 illustrates the conceptual view of both patterns.

Ff921087.bbfbea6f-4b25-4d01-8761-770a91838669(en-us,PandP.10).png

Figure2 
Conceptual view of the Service Locator and Dependency Injection patterns

For more information about these patterns, see Dependency Injection and Service Locator.

Examples

The following are example implementations of the Inversion of Control pattern:

  • In the Configuration Modularity QuickStarts, the class ModuleA defined in the ModuleA project uses dependency injection to obtain a reference to the region manager service, as shown in the following code.
     
    public class ModuleA : IModule
    {
        private readonly IRegionManager _regionManager;
    
        public ModuleA(IRegionManager regionManager)
        {
            _regionManager = regionManager;
        }
    
        ...
    }
    
    

    Because the ModuleA class is instantiated by a container and an instance of the region manager service is registered with the container, the ModuleA class receives a valid instance of the region manager service when it is constructed. Note that a mock instance of the region manager service can be supplied when testing the ModuleA class by passing the mock instance in the constructor's parameter.

  • The following code, extracted from the NewsModule class of the Stock Trader Reference Implementation (this class is located at StockTraderRI.Modules.News\NewsModule.cs), shows how an instance that implements the INewsController interface is obtained using the service locator pattern. The variable _container holds an instance to a container that has logic to locate a valid instance of the requested type.
     
    public void Initialize()
    {
        RegisterViewsAndServices();
        INewsController controller = _container.Resolve<INewsController>();
        controller.Run();
    }
    
    

    Note that for testing purposes, you could configure the container to return a mock instance that implements the INewsController interface instead of the real implementation. This enables you to test the NewsModule class in isolation. The following code, extracted from the NewsModuleFixture test class (located in StockTraderRI.Modules.News.Tests\NewsModuleFixture.cs), shows how the NewsModule class can be tested in isolation using a mock instance for the INewsController interface.

     
    [TestMethod]
    public void InitCallsRunOnNewsController()
    {
        MockUnityResolver container = new MockUnityResolver();
        var controller = new MockNewsController();
        container.Bag.Add(typeof(INewsController), controller);
        var newsModule = new NewsModule(container);
    
        newsModule.Initialize();
    
        Assert.IsTrue(controller.RunCalled);
    }
    
    

Liabilities

The Inversion of Control pattern has the following liabilities:

  • You need to implement a mechanism that provides the dependencies that are required by the object that is being initialized.
  • There is added complexity to the source code, which makes it harder to understand.
0 Dislike
Follow 2

Please Enter a comment

Submit

Other Lessons for You

Why a function in C# requires "Return type"??
- Basically , a Method is a piece of code used for the re-usability purpose. - Method is of 2 types Function and Procedure - Function is a method which returns a value to the calling place Function...

What Should I Learn in 2025 for Frontend or Web Technology?
If you're wondering what to focus on in 2025 to excel in frontend development, here's a concise guide: 1. React.js React remains one of the most in-demand technologies for building modern web applications....

CLR [ Common Language Runtime ] and it's properties
CLR is one of the components of the .NET framework which provides an environment to execute the .NET code or the managed code. , CLR helps in converting the MSIL/CIL code into native code and running...

"foreach" loop in C#
foreach is a looping statement : repeats a group of statements for each element in an array or an object collection. (or) used to iterate through the collection/ an array to get the required information. Advantages: Easy...

Steps to fill drop-down value from database to view page in ASP.Net MVC Application
In simple few steps you can fill the dynamic data from database to HTML page in MVC Application Write connection string in web config file Create table related getter setter in model Fetch data...

Looking for .Net Training ?

Learn from Best Tutors on UrbanPro.

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you
X

Looking for .Net Training Classes?

The best tutors for .Net Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn .Net Training with the Best Tutors

The best Tutors for .Net Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more