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,

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 = ON) ON [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. namespace App.Repository
  8. {
  9. public interface ICustomerRepository
  10. {
  11. IQueryable<Customer> GetAllCustomer();
  12. }
  13. }

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. namespace App.Repository
  8. {
  9. public class CustomerRepository : ICustomerRepository
  10. {
  11. DBCustomerEntities db = new DBCustomerEntities();
  12. public IQueryable<Customer> GetAllCustomer()
  13. {
  14. return db.Customers.AsQueryable();
  15. }
  16. }
  17. }

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

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

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. <context>
  11. <resource uri="config://spring/objects"/>
  12. </context>
  13. <objects xmlns="http://www.springframework.net">
  14. <object name="CustomerRepositoryService"
  15. type="App.Repository.CustomerRepository,App.Repository"/>
  16. <object name="CustomerController" type="SpringNetMVC5.Controllers.CustomerController, SpringNetMVC5" singleton="false">
  17. <property name="CustomerRepository" ref="CustomerRepositoryService"/>
  18. </object>
  19. </objects>
  20. </spring>
  21. <!-- 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. namespace SpringNetMVC5
  9. {
  10. public class MvcApplication : System.Web.HttpApplication
  11. {
  12. protected void Application_Start()
  13. {
  14. AreaRegistration.RegisterAllAreas();
  15. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  16. RouteConfig.RegisterRoutes(RouteTable.Routes);
  17. BundleConfig.RegisterBundles(BundleTable.Bundles);
  18. ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));
  19. }
  20. }
  21. }

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. namespace SpringNetMVC5.Controllers
  8. {
  9. public class CustomerController : Controller
  10. {
  11. public ICustomerRepository CustomerRepository { get; set; }
  12. // GET: Customer
  13. public ActionResult Index()
  14. {
  15. var customerList = CustomerRepository.GetAllCustomer();
  16. return View(customerList);
  17. }
  18. }
  19. }

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

Output

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

Spring.NET