Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring.NET DI With ASP.NET MVC5

DZone's Guide to

Spring.NET DI With ASP.NET MVC5

In this article, we offer a quick tutorial on how to implement a Spring.NET IOC container/dependency injection in ASP.NET MVC 5.

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

Introduction

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

What’s Spring.NET?

Spring.NET is an open-source application framework that 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 increase development productivity and improve application quality and performance.

Image title

In this article, we are going to:

  • Create a database.
  • Create an MVC application.
  • Configure Entity Framework ORM.
  • Create a repository.
  • Configure Spring.NET.
  • Create a controller.

SQL Database Part

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

Create a Database

USE [master]  
GO  
  
/****** Object:  Database [DBCustomer]    Script Date: 3/19/2017 3:54:44 AM ******/  
CREATE DATABASE [DBCustomer]  
 CONTAINMENT = NONE  
 ON  PRIMARY   
( NAME = N'DBCustomer', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
 LOG ON   
( 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%)  
GO  
  
ALTER DATABASE [DBCustomer] SET COMPATIBILITY_LEVEL = 110  
GO  
  
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
begin  
EXEC [DBCustomer].[dbo].[sp_fulltext_database] @action = 'enable'  
end  
GO  
  
ALTER DATABASE [DBCustomer] SET ANSI_NULL_DEFAULT OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET ANSI_NULLS OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET ANSI_PADDING OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET ANSI_WARNINGS OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET ARITHABORT OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET AUTO_CLOSE OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET AUTO_CREATE_STATISTICS ON   
GO  
  
ALTER DATABASE [DBCustomer] SET AUTO_SHRINK OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS ON   
GO  
  
ALTER DATABASE [DBCustomer] SET CURSOR_CLOSE_ON_COMMIT OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET CURSOR_DEFAULT  GLOBAL   
GO  
  
ALTER DATABASE [DBCustomer] SET CONCAT_NULL_YIELDS_NULL OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET NUMERIC_ROUNDABORT OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET QUOTED_IDENTIFIER OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET RECURSIVE_TRIGGERS OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET  DISABLE_BROKER   
GO  
  
ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET DATE_CORRELATION_OPTIMIZATION OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET TRUSTWORTHY OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET ALLOW_SNAPSHOT_ISOLATION OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET PARAMETERIZATION SIMPLE   
GO  
  
ALTER DATABASE [DBCustomer] SET READ_COMMITTED_SNAPSHOT OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET HONOR_BROKER_PRIORITY OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET RECOVERY SIMPLE   
GO  
  
ALTER DATABASE [DBCustomer] SET  MULTI_USER   
GO  
  
ALTER DATABASE [DBCustomer] SET PAGE_VERIFY CHECKSUM    
GO  
  
ALTER DATABASE [DBCustomer] SET DB_CHAINING OFF   
GO  
  
ALTER DATABASE [DBCustomer] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
GO  
  
ALTER DATABASE [DBCustomer] SET TARGET_RECOVERY_TIME = 0 SECONDS   
GO  
  
ALTER DATABASE [DBCustomer] SET  READ_WRITE   
GO  
Create Tables  
  
USE [DBCustomer]  
GO  
  
/****** Object:  Table [dbo].[Customer]    Script Date: 3/19/2017 3:55:15 AM ******/  
SET ANSI_NULLS ON  
GO  
  
SET QUOTED_IDENTIFIER ON  
GO  
  
SET ANSI_PADDING ON  
GO  
  
CREATE TABLE [dbo].[Customer](  
    [CustID] [int] IDENTITY(1,1) NOT NULL,  
    [FirstName] [varchar](50) NULL,  

    [LastName] [varchar](50) NULL,  
    [Email] [varchar](50) NULL,  
    [Country] [varchar](50) NULL,  
 CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED   
(  
    [CustID] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  
  
GO  
  
SET ANSI_PADDING OFF  
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.

Image title

Next, a new window will pop up for selecting the template. We are going choose the MVC template and click OK.

Image title

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

Image title

Our class library named App.Repository will look like this.

Image title

Configuring EntityFramework ORM

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

Image title

Next, we need to choose EF Designer from the database as a model contain.

Image title

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

Image title

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

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

Image title

Image title

Create Repository

ICustomerRepository.cs

using App.Repository.Mapping_EDMX;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App.Repository
{
   public interface ICustomerRepository
    {
        IQueryable<Customer> GetAllCustomer();
    }
}

CustomerRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using App.Repository.Mapping_EDMX;

namespace App.Repository
{
    public class CustomerRepository : ICustomerRepository
    {
        DBCustomerEntities db = new DBCustomerEntities();
        public IQueryable<Customer> GetAllCustomer()
        {
            return db.Customers.AsQueryable();
        }
    }
}

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

Configuring Spring.NET

Image title

You can get Spring.NET by using the package manager console, then running the following command:

PM> install-package spring.core 

Once Sprint.NET is installed, we are going to add a class that handles the Spring.NET application context.

SpringApplicationContext.cs

using Spring.Context;
using Spring.Context.Support;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SpringNetMVC5
{
    /// <summary>
    /// Spring Application Context.
    /// </summary>
    public static class SpringApplicationContext
    {
        /// <summary>
        ///
        /// </summary>
        private static IApplicationContext Context { get; set; }

        /// <summary>
        /// Returns a boolean value if the current application context contains an named object.
        /// </summary>
        /// <param name=”objectName”>Accepts the name of the object to check.</param>
        public static bool Contains(string objectName)
        {
            SpringApplicationContext.EnsureContext();
            return SpringApplicationContext.Context.ContainsObject(objectName);
        }

        /// <summary>
        /// Return a instance of an object in the context by the specified name.
        /// </summary>
        /// <param name=”objectName”>Accepts a string object name.</param>
        public static object Resolve(string objectName)
        {
            SpringApplicationContext.EnsureContext();
            return SpringApplicationContext.Context.GetObject(objectName);
        }

        /// <summary>
        /// Return a instance of an object in the context by the specified name and type.
        /// </summary>
        /// <typeparam name=”T”>Accepts the type of the object to resolve.</typeparam>
        /// <param name=”objectName”>Accepts a string object name.</param>
        public static T Resolve<T>(string objectName)
        {
            return (T)SpringApplicationContext.Resolve(objectName);
        }
        /// <summary>
        ///
        /// </summary>
        private static void EnsureContext()
        {
            if (SpringApplicationContext.Context == null)
            {
                SpringApplicationContext.Context = ContextRegistry.GetContext();
            }
        }
    }
}

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

SpringControllerFactory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SpringNetMVC5
{
    public class SpringControllerFactory : DefaultControllerFactory, IControllerFactory
    {

        #region IControllerFactory Memebers
        IController IControllerFactory.CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            IController controller = null;
            string controllerClassName = string.Format("{0}Controller", controllerName);

            if (SpringApplicationContext.Contains(controllerClassName))
            {
                controller = SpringApplicationContext.Resolve<IController>(controllerClassName);
            }
            else
            {
                try
                {
                    controller = base.CreateController(requestContext, controllerName);
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
            return controller;
        }
        #endregion

        void IControllerFactory.ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;
            if (disposable != null)
            {
                disposable.Dispose();
            }
        }
    }
}

Web.config

Add the following spring config to <configSections></configSections>

<!-- SPRING -->
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
    </sectionGroup>
<!--END SPRING-->

Here, we are going to configure a Spring object by adding the following config to <configuration></configuration>.

<!—Spring Configuration -->
  <spring>

    <context>

      <resource uri="config://spring/objects"/>
    </context>

    <objects xmlns="http://www.springframework.net">

      <object name="CustomerRepositoryService"
        type="App.Repository.CustomerRepository,App.Repository"/>

      <object name="CustomerController" type="SpringNetMVC5.Controllers.CustomerController, SpringNetMVC5" singleton="false">
        <property name="CustomerRepository" ref="CustomerRepositoryService"/>
      </object>

    </objects>

  </spring>
<!-- END Spring Configuration -->

Note: Please, make sure that the SpringControllerFactory class has been added at the Application_Start() method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SpringNetMVC5
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));
        }
    }
}

Create a Controller

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

Image title

Enter the Controller name (‘CustomerController’).

Image title

CustomerController.cs

using App.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SpringNetMVC5.Controllers
{
    public class CustomerController : Controller
    {
        public ICustomerRepository CustomerRepository { get; set; }

        // GET: Customer
        public ActionResult Index()
        {
            var customerList = CustomerRepository.GetAllCustomer();

            return View(customerList);
        }
    }
}

Here, I am creating an 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 customer data.

Adding View

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

Image title

Index.cshtml

@model IEnumerable<App.Repository.Mapping_EDMX.Customer>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.CustID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Country)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CustID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Country)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

Output

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

Image title

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
spring.net ,dependecy injection ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}