Spring.NET DI With ASP.NET MVC 5

Introduction

In this article, we will learn how to implement Spring.NET IOC container/ Dependency Injection in ASP.NET MVC 5. In this example, we are going to create a basic application, and share the different steps to perform Spring.NET IOC in ASP.NET MVC5.

What’s Spring.NET?

Spring.NET is an open source Application Framework, which makes building enterprise .NET Applications easier.

Providing components based on proven design patterns that can be integrated into all tiers of your Application architecture, Spring helps in increasing development productivity and improving the application quality and performance. 

Spring.NET

In this article, we are going to,

  • Create a database.
  • Create MVC Application.
  • Configuring Entity Framework ORM.
  • Create repository.
  • Configuring Spring.NET.
  • Create controller.

SQL database part

Here, you can find the scripts to create a database and a table.

Create database 

  1. USE [master]  
  2. GO  
  3. /****** Object: Database[DBCustomer] Script Date: 3/19/2017 3:54:44 AM ******/  
  4. CREATEDATABASE [DBCustomer]  
  5. CONTAINMENT = NONE  
  6. ON PRIMARY  
  7. NAME= N'DBCustomer', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  8. LOG ON  
  9. NAME= N'DBCustomer_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer_log.ldf'SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  10. GO  
  11. ALTERDATABASE[DBCustomer] SET COMPATIBILITY_LEVEL = 110  
  12. GO  
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC[DBCustomer].[dbo].[sp_fulltext_database] @action'enable'  
  16. end  
  17. GO  
  18. ALTERDATABASE[DBCustomer] SET ANSI_NULL_DEFAULT OFF  
  19. GO  
  20. ALTERDATABASE[DBCustomer] SET ANSI_NULLS OFF  
  21. GO  
  22. ALTERDATABASE[DBCustomer] SET ANSI_PADDING OFF  
  23. GO  
  24. ALTERDATABASE[DBCustomer] SET ANSI_WARNINGS OFF  
  25. GO  
  26. ALTERDATABASE[DBCustomer] SET ARITHABORT OFF  
  27. GO  
  28. ALTERDATABASE[DBCustomer] SET AUTO_CLOSE OFF  
  29. GO  
  30. ALTERDATABASE[DBCustomer] SET AUTO_CREATE_STATISTICS ON  
  31. GO  
  32. ALTERDATABASE[DBCustomer] SET AUTO_SHRINK OFF  
  33. GO  
  34. ALTERDATABASE[DBCustomer] SET AUTO_UPDATE_STATISTICS ON  
  35. GO  
  36. ALTERDATABASE[DBCustomer] SET CURSOR_CLOSE_ON_COMMIT OFF  
  37. GO  
  38. ALTERDATABASE[DBCustomer] SET CURSOR_DEFAULT GLOBAL  
  39. GO  
  40. ALTERDATABASE[DBCustomer] SET CONCAT_NULL_YIELDS_NULL OFF  
  41. GO  
  42. ALTERDATABASE[DBCustomer] SET NUMERIC_ROUNDABORT OFF  
  43. GO  
  44. ALTERDATABASE[DBCustomer] SET QUOTED_IDENTIFIER OFF  
  45. GO  
  46. ALTERDATABASE[DBCustomer] SET RECURSIVE_TRIGGERS OFF  
  47. GO  
  48. ALTERDATABASE[DBCustomer] SET DISABLE_BROKER  
  49. GO  
  50. ALTERDATABASE[DBCustomer] SET AUTO_UPDATE_STATISTICS_ASYNC OFF  
  51. GO  
  52. ALTERDATABASE[DBCustomer] SET DATE_CORRELATION_OPTIMIZATION OFF  
  53. GO  
  54. ALTERDATABASE[DBCustomer] SET TRUSTWORTHY OFF  
  55. GO  
  56. ALTERDATABASE[DBCustomer] SET ALLOW_SNAPSHOT_ISOLATION OFF  
  57. GO  
  58. ALTERDATABASE[DBCustomer] SET PARAMETERIZATION SIMPLE  
  59. GO  
  60. ALTERDATABASE[DBCustomer] SET READ_COMMITTED_SNAPSHOT OFF  
  61. GO  
  62. ALTERDATABASE[DBCustomer] SET HONOR_BROKER_PRIORITY OFF  
  63. GO  
  64. ALTERDATABASE[DBCustomer] SET RECOVERY SIMPLE  
  65. GO  
  66. ALTERDATABASE[DBCustomer] SET MULTI_USER  
  67. GO  
  68. ALTERDATABASE[DBCustomer] SET PAGE_VERIFY CHECKSUM  
  69. GO  
  70. ALTERDATABASE [DBCustomer] SET DB_CHAINING OFF  
  71. GO  
  72. ALTERDATABASE [DBCustomer] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )  
  73. GO  
  74. ALTERDATABASE [DBCustomer] SET TARGET_RECOVERY_TIME = 0 SECONDS  
  75. GO  
  76. ALTERDATABASE [DBCustomer] SET READ_WRITE  
  77. GO  
  78. CreateTables  
  79. USE [DBCustomer]  
  80. GO  
  81. /****** Object: Table[dbo].[Customer] Script Date: 3/19/2017 3:55:15 AM ******/  
  82. SETANSI_NULLS ON  
  83. GO  
  84. SETQUOTED_IDENTIFIER ON  
  85. GO  
  86. SETANSI_PADDING ON  
  87. GO  
  88. CREATETABLE [dbo].[Customer](  
  89. [CustID] [int] IDENTITY(1,1) NOT NULL,  
  90. [FirstName] [varchar](50) NULL,  
  91. [LastName] [varchar](50) NULL,  
  92. [Email] [varchar](50) NULL,  
  93. [Country] [varchar](50) NULL,  
  94. CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED  
  95. (  
  96. [CustID] ASC  
  97. )WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  98. ON[PRIMARY]  
  99. GO  
  100. SETANSI_PADDING OFF  
  101. GO  

Create your MVC Application

Open Visual Studio and select File >> New Project.

The New Project Window will pop up. Select ASP.NET Web Application (.NET Framework), name your project and click OK.

Spring.NET

Now, new dialog will pop up to select the template. We are going to choose MVC template and click OK button.

Spring.NET

After creating our project, we are going to add Class Library. For this, right click on the project name >> New Project >> Class Library.

Spring.NET

Our class library named App.Repository will look, as shown below.

Spring.NET

Configuring EntityFramework ORM

To add ADO.NET Entity Framework, right click on Mapping EDMX file >> Add >> Add New Item. Dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model and enter a name for your Dbcontext model as DbCustomer.

Spring.NET

Now, we need to choose EF Designer from the database, which model contains.

Spring.NET

As you can see below, we need to select Server name, then via dropdown list; connect to a database panel. You should choose your database name. Finally, click OK.

Spring.NET

Now, the dialog Entity Data Model Wizard will pop up to choose the object, which we need to use. In our case, we are going to choose Customer table and click Finish button.

Finally, we see that EDMX model generates a Customer class.

Spring.NET

Spring.NET

Create Repository

ICustomerRepository.cs 

  1. using App.Repository.Mapping_EDMX;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace App.Repository  
  9. {  
  10.    public interface ICustomerRepository  
  11.     {  
  12.         IQueryable<Customer> GetAllCustomer();  
  13.     }  
  14. }   

CustomerRepository.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using App.Repository.Mapping_EDMX;  
  7.   
  8. namespace App.Repository  
  9. {  
  10.     public class CustomerRepository : ICustomerRepository  
  11.     {  
  12.         DBCustomerEntities db = new DBCustomerEntities();  
  13.         public IQueryable<Customer> GetAllCustomer()  
  14.         {  
  15.             return db.Customers.AsQueryable();  
  16.         }  
  17.     }  
  18. }   

The next step is to configure Spring.NET IOC. Let’s start.

Configuring Spring.NET

Spring.NET

You can get Spring.NET by using Package Manager Console and run the command given below:

PM> install-package spring.core

Once Sprint.NET is installed. We are going to add class, which handles Spring.NET Application context.

SpringApplicationContext.cs 

  1. using Spring.Context;  
  2. using Spring.Context.Support;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace SpringNetMVC5  
  9. {  
  10.     /// <summary>  
  11.     /// Spring Application Context.  
  12.     /// </summary>  
  13.     public static class SpringApplicationContext  
  14.     {  
  15.         /// <summary>  
  16.         ///  
  17.         /// </summary>  
  18.         private static IApplicationContext Context { get; set; }  
  19.   
  20.         /// <summary>  
  21.         /// Returns a boolean value if the current application context contains an named object.  
  22.         /// </summary>  
  23.         /// <param name=”objectName”>Accepts the name of the object to check.</param>  
  24.         public static bool Contains(string objectName)  
  25.         {  
  26.             SpringApplicationContext.EnsureContext();  
  27.             return SpringApplicationContext.Context.ContainsObject(objectName);  
  28.         }  
  29.   
  30.         /// <summary>  
  31.         /// Return a instance of an object in the context by the specified name.  
  32.         /// </summary>  
  33.         /// <param name=”objectName”>Accepts a string object name.</param>  
  34.         public static object Resolve(string objectName)  
  35.         {  
  36.             SpringApplicationContext.EnsureContext();  
  37.             return SpringApplicationContext.Context.GetObject(objectName);  
  38.         }  
  39.   
  40.         /// <summary>  
  41.         /// Return a instance of an object in the context by the specified name and type.  
  42.         /// </summary>  
  43.         /// <typeparam name=”T”>Accepts the type of the object to resolve.</typeparam>  
  44.         /// <param name=”objectName”>Accepts a string object name.</param>  
  45.         public static T Resolve<T>(string objectName)  
  46.         {  
  47.             return (T)SpringApplicationContext.Resolve(objectName);  
  48.         }  
  49.         /// <summary>  
  50.         ///  
  51.         /// </summary>  
  52.         private static void EnsureContext()  
  53.         {  
  54.             if (SpringApplicationContext.Context == null)  
  55.             {  
  56.                 SpringApplicationContext.Context = ContextRegistry.GetContext();  
  57.             }  
  58.         }  
  59.     }  
  60. }   

In the next step we need to add a controller factory that allows Spring.NET to manage your controllers.

SpringControllerFactory.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace SpringNetMVC5  
  8. {  
  9.     public class SpringControllerFactory : DefaultControllerFactory, IControllerFactory  
  10.     {  
  11.  
  12.         #region IControllerFactory Memebers  
  13.         IController IControllerFactory.CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)  
  14.         {  
  15.             IController controller = null;  
  16.             string controllerClassName = string.Format("{0}Controller", controllerName);  
  17.   
  18.             if (SpringApplicationContext.Contains(controllerClassName))  
  19.             {  
  20.                 controller = SpringApplicationContext.Resolve<IController>(controllerClassName);  
  21.             }  
  22.             else  
  23.             {  
  24.                 try  
  25.                 {  
  26.                     controller = base.CreateController(requestContext, controllerName);  
  27.                 }  
  28.                 catch (Exception ex)  
  29.                 {  
  30.   
  31.                     throw ex;  
  32.                 }  
  33.             }  
  34.             return controller;  
  35.         }  
  36.         #endregion  
  37.   
  38.         void IControllerFactory.ReleaseController(IController controller)  
  39.         {  
  40.             IDisposable disposable = controller as IDisposable;  
  41.             if (disposable != null)  
  42.             {  
  43.                 disposable.Dispose();  
  44.             }  
  45.         }  
  46.     }  
  47. }  

 Web.config

Add the spring config given below to <configSections></configSections> 

  1. <!-- SPRING -->  
  2.     <sectionGroup name="spring">  
  3.       <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>  
  4.       <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>  
  5.     </sectionGroup>  
  6. <!--END SPRING-->  
  7. Here, we are going to configure spring object by adding the following config to <configuration></configuration>.  
  8. <!—Spring Configuration -->  
  9.   <spring>  
  10.   
  11.     <context>  
  12.        
  13.       <resource uri="config://spring/objects"/>  
  14.     </context>  
  15.   
  16.     <objects xmlns="http://www.springframework.net">  
  17.   
  18.       <object name="CustomerRepositoryService"  
  19.         type="App.Repository.CustomerRepository,App.Repository"/>  
  20.   
  21.       <object name="CustomerController" type="SpringNetMVC5.Controllers.CustomerController, SpringNetMVC5" singleton="false">  
  22.         <property name="CustomerRepository" ref="CustomerRepositoryService"/>  
  23.       </object>  
  24.   
  25.     </objects>  
  26.   
  27.   </spring>  
  28. <!-- END Spring Configuration -->   

Note

Please make sure that SpringControllerFactory class has been added at Application_Start() method. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Optimization;  
  7. using System.Web.Routing;  
  8.   
  9. namespace SpringNetMVC5  
  10. {  
  11.     public class MvcApplication : System.Web.HttpApplication  
  12.     {  
  13.         protected void Application_Start()  
  14.         {  
  15.             AreaRegistration.RegisterAllAreas();  
  16.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  17.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  18.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  19.   
  20.             ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));  
  21.         }  
  22.     }  
  23. }   

Create a controller

Now, we are going to create a controller. Right click on the controllers folder >> Add >> Controller>> select MVC5 Controller>> Empty >> click Add.

Spring.NET

Enter Controller name (‘CustomerController’).

Spring.NET

CustomerController.cs 

  1. using App.Repository;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace SpringNetMVC5.Controllers  
  9. {  
  10.     public class CustomerController : Controller  
  11.     {  
  12.         public ICustomerRepository CustomerRepository { get; set; }  
  13.   
  14.         // GET: Customer  
  15.         public ActionResult Index()  
  16.         {  
  17.             var customerList = CustomerRepository.GetAllCustomer();  
  18.   
  19.             return View(customerList);  
  20.         }  
  21.     }  
  22. }   

Here, I am creating Index() action to retrieve data from Customer table in JSON format. As you can see, I have used CustomerRepository as a property, which is injected by Spring.NET in order to return the customers data.

Adding View

It’s easy to do. Just right click on Index() action, select Add View and the dialog will pop up. Write a name for your view and finally click Add.

Spring.NET

Index.cshtml

  1. @model IEnumerable<App.Repository.Mapping_EDMX.Customer>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. <table class="table">  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.CustID)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.FirstName)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.LastName)  
  22.         </th>  
  23.         <th>  
  24.             @Html.DisplayNameFor(model => model.Email)  
  25.         </th>  
  26.         <th>  
  27.             @Html.DisplayNameFor(model => model.Country)  
  28.         </th>  
  29.         <th></th>  
  30.     </tr>  
  31.   
  32. @foreach (var item in Model) {  
  33.     <tr>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.CustID)  
  36.         </td>  
  37.         <td>  
  38.             @Html.DisplayFor(modelItem => item.FirstName)  
  39.         </td>  
  40.         <td>  
  41.             @Html.DisplayFor(modelItem => item.LastName)  
  42.         </td>  
  43.         <td>  
  44.             @Html.DisplayFor(modelItem => item.Email)  
  45.         </td>  
  46.         <td>  
  47.             @Html.DisplayFor(modelItem => item.Country)  
  48.         </td>  
  49.         <td>  
  50.             @Html.ActionLink("Edit""Edit"new { /* id=item.PrimaryKey */ }) |  
  51.             @Html.ActionLink("Details""Details"new { /* id=item.PrimaryKey */ }) |  
  52.             @Html.ActionLink("Delete""Delete"new { /* id=item.PrimaryKey */ })  
  53.         </td>  
  54.     </tr>  
  55. }  
  56.   
  57. </table>   

Output

Now, you can run your Application. Let’s see the output.

Spring.NET


Similar Articles