Introduction
Why code against interfaces but against concrete implementations? This is the most common question asked by fresh grads. In this article, we will answer this question and also teach you how to implement Ninject Dependency Injection using MVC with a C# example. Dependency Injection is a technique used to reduce coupling between classes of a program. We will now discuss what is Dependency Injection and why should we use it in our programs. After explaining why it is beneficial, we will dive into how to implement Ninject Dependency Injection in MVC with the help of an example.What is Dependency Injection?
In general, dependency injection allows you to modify classes at the run time of a program. It allows the removal of hard-coded relations between different classes, and change or modify them at the run time. In a generalised explanation, by using dependency injection can allow multiple configurations to be loaded at the run time by having multiple class object scenarios. We will explain Dependency Injection by splitting the two words. Dependency, it is the object (or a service) which is required by a class (or a client). Injection, it is the technique to pass the object to the class, or in layman’s language, providing service to a client.Why use Dependency Injection?
When an object is needed in a class, the class constructor can be used to construct and design the object every time it is required. However, this could slow down the program in long and complex situations and also use more storage than necessary. By using Dependency Injection, we can pass pre-defined and constructed objects to classes for processing. We can design the class with different configurations to be used on different kind of objects in multiple situations. Some of the technical advantages of using Dependency Injection are written below.- Dependency Injection allows setting multiple configurations to be used and modified at the run time in a program.
- Different configurations can be saved externally in configuration files which allow the program to be reconfigured at runtime.
- By using Dependency Injection, it becomes easy to reset information and knowledge cached by the services in the program. This reduces the chances of functions and classes getting defected from design changes in a program. It also makes it easy to reuse old data.
- By using Dependency Injection frameworks, multiple developers can work at different classes of a program independently as the objects will always be passed by using dependency injection. However, the interface used by the classes should work the same way. The most commonly used example of this advantage is plugins. Plugins are developed by third-party developers who do not belong or know the original developer personally. They only follow the same interface and dependency injection framework.
Now download the MVC project. You can find the download button at the bottom of the page. After clicking on the button, you will be redirected to the file download page on Dropbox. Select Direct download to save the file on your PC.
Now extract the downloaded zip file on your PC and open the project file from the extracted folder. It will open in Microsoft Visual Studio.
Step 2: Now Google Ninject Nuget MVC 4 and open the first link or directly open it by clicking here.
Copy the code syntax as shown in the video to your code and let it process.
It will now automatically receive the dependency files and install required plugins to your MVC.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(slnMvcArea.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(slnMvcArea.App_Start.NinjectWebCommon), "Stop")] namespace slnMvcArea.App_Start { using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; using TC.DataService; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); ////// Starts the application /// public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } ////// Stops the application. /// public static void Stop() { bootstrapper.ShutDown(); } ////// Creates the kernel that will manage your application. /// ///The created kernel. private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); kernel.Bind<IClass1>().To<Class1>();RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// /// Load your modules or register your services here! /// /// The kernel. private static void RegisterServices(IKernel kernel) { } } }
Step 3: As you can see in the video & also demonstrating in this step also, we had already created a data service using interfacing to implement Ninject.
Define Interface Class:
public interface IClass1 { string GetMyFirstValue(); }
Now, Implement Interface Class:
public class Class1 : IClass1 { public string GetMyFirstValue() { return "My First Ninject implementation in mvc application!"; } }
Step 4: After completing these steps, you will see the NinjectWebCommon.cs in the App_Start folder.
Step 5: After installing, we have to register the interface for the new class of Ninject and implement it in the MVC application.
Step 6: Now we will execute and test our code to see if the program is working properly or not. If everything is done right, you will see the “My First Ninject implementation in MVC application” result in your browser as seen in the video tutorial.
Now call it on your Home Page
public ActionResult Index() { ViewBag.msg = _IClass1.GetMyFirstValue(); return View(); }
Post A Comment:
0 comments: