in

Chennai .Net User Group

A platform that enables you to Learn, Share & Grow (India's first .Net user group)

Shiju Varghese's Blog

January 2011 - Posts

  • Dependency Injection in ASP.NET MVC 3 using DependencyResolver and ControllerActivator

    In my previous examples for dependency injection in ASP.NET MVC, I have used an approach where creating a custom controller factory deriving from DefaultControllerFactory and override the GetControllerInstance method for dependency injection. But ASP.NET MVC 3 is providing great support for dependency injection with very nice abstraction. In this post, I will demonstrate how to achieve dependency injection using two interfaces introduced in ASP.NET MVC 3 - IDependencyResolver and IControllerActivator. Unity 2.0 will be using as the dependency injection  container for this demo app.

    Custom Controller Activator class using IControllerActivator

    ASP.NET MVC 3 has introduced a new interface IControllerActivator which lets you activate controllers with custom behavior and can be use it for dependency  injection purpose.The IControllerActivator interface is discoverable using the dependency resolver. Let’s create a custom controller activator class by deriving from IControllerActivator intreface

     

    1. public class CustomControllerActivator : IControllerActivator
    2.     {        
    3.         IController IControllerActivator.Create(
    4.             System.Web.Routing.RequestContext requestContext,
    5.             Type controllerType)
    6.         {
    7.             return DependencyResolver.Current
    8.                 .GetService(controllerType) as IController;
    9.         }      
    10.     }

     

    Custom Dependency Resolver class using IDependencyResolver

    ASP.NET MVC 3 has introduced a new interface IDependencyResolver which exposes two methods - GetService and GetServices.The GetService method resolves singly registered services that support arbitrary object creation and the GetServices resolves multiply registered services. Implementations of the IDependencyResolver interface should delegate to the underlying dependency injection container to provide the registered service for the requested type. When there are no registered services of the requested type, the ASP.NET MVC framework expects implementations of this interface to return null from GetService and to return an empty collection from GetServices. Let’s create a custom dependency resolver class by deriving from IDependencyResolver intreface in order to working with Unity to providing dependency injection.

     

    1. public class UnityDependencyResolver : IDependencyResolver
    2. {        
    3.     IUnityContainer container;       
    4.     public UnityDependencyResolver(IUnityContainer container)
    5.     {
    6.         this.container = container;
    7.     }
    8.  
    9.     public object GetService(Type serviceType)
    10.     {
    11.         try
    12.         {
    13.             return container.Resolve(serviceType);
    14.         }
    15.         catch
    16.         {               
    17.             return null;
    18.         }
    19.     }
    20.  
    21.     public IEnumerable<object> GetServices(Type serviceType)
    22.     {
    23.         try
    24.         {
    25.             return container.ResolveAll(serviceType);
    26.         }
    27.         catch
    28.         {                
    29.             return new List<object>();
    30.         }
    31.     }
    32. }

     

    Configure the Unity container with DependencyResolver.SetResolver Method


    The below code configure the Unity container using SetResolver method of DependencyResolver class

     

    1. protected void Application_Start()
    2. {
    3.     AreaRegistration.RegisterAllAreas();
    4.     RegisterGlobalFilters(GlobalFilters.Filters);
    5.     RegisterRoutes(RouteTable.Routes);
    6.     IUnityContainer container = GetUnityContainer();
    7.     DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    8. }

     

    The SetResolver method of DependencyResolver class provides a registration point for dependency injection containers. In this method, we configure the UnityDependencyResolver class for providing dependency injection with Unity 2.0. The SetResolver method will be working with any dependency injection container.If you want to use StructureMap  as the dependency injection container, you can create a dependency resolver class in order to working with StructureMap  by deriving IDependencyResolver intreface and later you can configure this class with SetResolver method. The ASP.NET MVC 3 is providing an excellent support for working  with dependency injection containers.

    The GetUnityContainer method is shown below

     

    1. private IUnityContainer GetUnityContainer()
    2.  {
    3.      //Create UnityContainer          
    4.      IUnityContainer container = new UnityContainer()
    5.      .RegisterType<IControllerActivator, CustomControllerActivator>()
    6.      .RegisterType<IFormsAuthenticationService, FormsAuthenticationService>()
    7.      .RegisterType<IMembershipService, AccountMembershipService>()
    8.      .RegisterInstance<MembershipProvider>(Membership.Provider)
    9.      .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())
    10.      .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())
    11.      .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>())
    12.      .RegisterType<IExpenseRepository, ExpenseRepository>(new HttpContextLifetimeManager<IExpenseRepository>())
    13.      .RegisterType<ICategoryService, CategoryService>(new HttpContextLifetimeManager<ICategoryService>())
    14.      .RegisterType<IExpenseService, ExpenseService>(new HttpContextLifetimeManager<IExpenseService>());
    15.      return container;         
    16.  }

     

    In the above GetUnityContainer method, I added the registration for IControllerActivator type into the Unity container along with other types. This will use concrete class CustomControllerActivator for the type IControllerActivator.

    Source Code

    You can download the source code from my demo app for ASP.NET MVC 3 and EF Code First at http://efmvc.codeplex.com/

  • Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 2

    In my previous post Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1, we have discussed on how to work with ASP.NET MVC 3 and EF Code First for developing web apps. We have created generic repository and unit of work with EF Code First for our ASP.NET MVC 3 application and did basic CRUD operations against a simple domain entity. In this post, I will demonstrate on working with domain entity with deep object graph, Service Layer and View Models and will also complete the rest of the demo application. In the previous post, we have done CRUD operations against Category entity and this post will be focus on Expense entity those have an association with Category entity. You can download the source code from http://efmvc.codeplex.com .


    The following frameworks will be used for this step by step tutorial.


       1. ASP.NET MVC 3 RTM
       2. EF Code First CTP 5
       3. Unity 2.0

    Domain Model

    Category Entity

    1. public class Category
    2.   {
    3.       public int CategoryId { get; set; }
    4.       [Required(ErrorMessage = "Name Required")]
    5.       [StringLength(25, ErrorMessage = "Must be less than 25 characters")]
    6.       public string Name { get; set;}
    7.       public string Description { get; set; }
    8.       public virtual ICollection<Expense> Expenses { get; set; }
    9.   }

    Expense Entity

    1. public class Expense
    2.     {       
    3.         public int ExpenseId { get; set; }       
    4.         public string  Transaction { get; set; }
    5.         public DateTime Date { get; set; }
    6.         public double Amount { get; set; }
    7.         public int CategoryId { get; set; }
    8.         public virtual Category Category { get; set; }
    9.     }


    We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category.

    Repository class for Expense Transaction


    Let’s create repository class for handling CRUD operations for Expense entity

    1. public class ExpenseRepository : RepositoryBase<Expense>, IExpenseRepository
    2.     {
    3.     public ExpenseRepository(IDatabaseFactory databaseFactory)
    4.         : base(databaseFactory)
    5.         {
    6.         }           
    7.     }
    8. public interface IExpenseRepository : IRepository<Expense>
    9. {
    10. }

    Service Layer

    If you are new to Service Layer, checkout Martin Fowler's article Service Layer . According to Martin Fowler, Service Layer defines an application's boundary and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations. Controller classes should be lightweight and do not put much of business logic onto it. We can use the service layer as the business logic layer and can encapsulate the rules of the application.


    Let’s create a Service class for coordinates the transaction for Expense

    1. public interface IExpenseService
    2. {
    3.     IEnumerable<Expense> GetExpenses(DateTime startDate, DateTime ednDate);
    4.     Expense GetExpense(int id);        
    5.     void CreateExpense(Expense expense);
    6.     void DeleteExpense(int id);
    7.     void SaveExpense();
    8. }
    9. public class ExpenseService : IExpenseService
    10. {
    11.     private readonly IExpenseRepository expenseRepository;       
    12.     private readonly IUnitOfWork unitOfWork;
    13.     public ExpenseService(IExpenseRepository expenseRepository, IUnitOfWork unitOfWork)
    14.     {         
    15.         this.expenseRepository = expenseRepository;
    16.         this.unitOfWork = unitOfWork;
    17.     }
    18.     public IEnumerable<Expense> GetExpenses(DateTime startDate, DateTime endDate)
    19.     {
    20.         var expenses = expenseRepository.GetMany(exp => exp.Date >= startDate && exp.Date <= endDate);
    21.         return expenses;
    22.     }
    23.     public void CreateExpense(Expense expense)
    24.     {
    25.         expenseRepository.Add(expense);
    26.         unitOfWork.Commit();
    27.     }
    28.     public Expense GetExpense(int id)
    29.     {
    30.         var expense = expenseRepository.GetById(id);
    31.         return expense;
    32.     }
    33.     public void DeleteExpense(int id)
    34.     {
    35.         var expense = expenseRepository.GetById(id);
    36.         expenseRepository.Delete(expense);
    37.         unitOfWork.Commit();
    38.     }
    39.     public void SaveExpense()
    40.     {
    41.         unitOfWork.Commit();
    42.     }
    43. }

     

    View Model for Expense Transactions


    In real world ASP.NET MVC applications, we need to design model objects especially for our views. Our domain objects are mainly designed for the needs for domain model and it is representing the domain of our applications. On the other hand, View Model objects are designed for our needs for views. We have an Expense domain entity that has an association with Category. While we are creating a new Expense, we have to specify that in which Category belongs with the new Expense transaction. The user interface for Expense transaction will have form fields for representing the Expense entity and a CategoryId for representing the Category. So let's create view model for representing the need for Expense transactions.

    1. public class ExpenseViewModel
    2. {
    3.     public int ExpenseId { get; set; }
    4.  
    5.     [Required(ErrorMessage = "Category Required")]
    6.     public int CategoryId { get; set; }
    7.  
    8.     [Required(ErrorMessage = "Transaction Required")]
    9.     public string Transaction { get; set; }
    10.  
    11.     [Required(ErrorMessage = "Date Required")]
    12.     public DateTime Date { get; set; }
    13.  
    14.     [Required(ErrorMessage = "Amount Required")]
    15.     public double Amount { get; set; }
    16.  
    17.     public IEnumerable<SelectListItem> Category { get; set; }
    18. }


    The ExpenseViewModel is designed for the purpose of View template and contains the all validation rules. It has properties for mapping values to Expense entity and a property Category for binding values to a drop-down for list values of Category.


    Create Expense transaction

    Let’s create action methods in the ExpenseController for creating expense transactions

    1. public ActionResult Create()
    2. {
    3.     var expenseModel = new ExpenseViewModel();
    4.     var categories = categoryService.GetCategories();
    5.     expenseModel.Category = categories.ToSelectListItems(-1);
    6.     expenseModel.Date = DateTime.Today;
    7.     return View(expenseModel);
    8. }
    9. [HttpPost]
    10. public ActionResult Create(ExpenseViewModel expenseViewModel)
    11. {
    12.             
    13.         if (!ModelState.IsValid)
    14.         {
    15.             var categories = categoryService.GetCategories();
    16.             expenseViewModel.Category = categories.ToSelectListItems(expenseViewModel.CategoryId);
    17.             return View("Save", expenseViewModel);
    18.         }
    19.         Expense expense=new Expense();
    20.         ModelCopier.CopyModel(expenseViewModel,expense);
    21.         expenseService.CreateExpense(expense);
    22.         return RedirectToAction("Index");
    23.             
    24. }


    In the Create action method for HttpGet request, we have created an instance of our View Model ExpenseViewModel with Category information for the drop-down list and passing the Model object to View template. The extension method ToSelectListItems is shown below

     

    1. public static IEnumerable<SelectListItem> ToSelectListItems(
    2.         this IEnumerable<Category> categories, int  selectedId)
    3. {
    4.     return
    5.  
    6.         categories.OrderBy(category => category.Name)
    7.                 .Select(category =>
    8.                     new SelectListItem
    9.                     {
    10.                         Selected = (category.CategoryId == selectedId),
    11.                         Text = category.Name,
    12.                         Value = category.CategoryId.ToString()
    13.                     });
    14. }

    In the Create action method for HttpPost, our view model object ExpenseViewModel will map with posted form input values. We need to create an instance of Expense for the persistence purpose. So we need to copy values from ExpenseViewModel object to Expense object. ASP.NET MVC futures assembly provides a static class ModelCopier that can use for copying values between Model objects. ModelCopier class has two static methods - CopyCollection and CopyModel.CopyCollection method will copy values between two collection objects and CopyModel will copy values between two model objects. We have used CopyModel method of ModelCopier class for copying values from expenseViewModel object to expense object. Finally we did a call to CreateExpense method of ExpenseService class for persisting new expense transaction.

    List Expense Transactions


    We want to list expense transactions based on a date range. So let’s create action method for filtering expense transactions with a specified date range.

    1. public ActionResult Index(DateTime? startDate, DateTime? endDate)
    2. {
    3.     //If date is not passed, take current month's first and last dte
    4.     DateTime dtNow;
    5.     dtNow = DateTime.Today;
    6.     if (!startDate.HasValue)
    7.     {
    8.         startDate = new DateTime(dtNow.Year, dtNow.Month, 1);
    9.         endDate = startDate.Value.AddMonths(1).AddDays(-1);
    10.     }
    11.     //take last date of start date's month, if end date is not passed
    12.     if (startDate.HasValue && !endDate.HasValue)
    13.     {
    14.         endDate = (new DateTime(startDate.Value.Year, startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);
    15.     }
    16.     var expenses = expenseService.GetExpenses(startDate.Value ,endDate.Value);
    17.     //if request is Ajax will return partial view
    18.     if (Request.IsAjaxRequest())
    19.     {
    20.         return PartialView("ExpenseList", expenses);
    21.     }
    22.     //set start date and end date to ViewBag dictionary
    23.     ViewBag.StartDate = startDate.Value.ToShortDateString();
    24.     ViewBag.EndDate = endDate.Value.ToShortDateString();
    25.     //if request is not ajax
    26.     return View(expenses);
    27. }


    We are using the above Index Action method for both Ajax requests and normal requests. If there is a request for Ajax, we will call the PartialView ExpenseList.


    Razor Views for listing Expense information

    Let’s create view templates in Razor for showing list of Expense information

    ExpenseList.cshtml

    1. @model IEnumerable<MyFinance.Domain.Expense>
    2.  
    3. <table>
    4.         <tr>
    5.             <th>Actions</th>
    6.             <th>Category</th>
    7.             <th>
    8.                 Transaction
    9.             </th>
    10.             <th>
    11.                 Date
    12.             </th>
    13.             <th>
    14.                 Amount
    15.             </th>
    16.         </tr>
    17.  
    18.     @foreach (var item in Model) {
    19.     
    20.         <tr>
    21.             <td>
    22.                 @Html.ActionLink("Edit", "Edit",new { id = item.ExpenseId })
    23.                 @Ajax.ActionLink("Delete", "Delete", new { id = item.ExpenseId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divExpenseList" })
    24.             </td>
    25.              <td>
    26.                 @item.Category.Name
    27.             </td>
    28.             <td>
    29.                 @item.Transaction
    30.             </td>
    31.             <td>
    32.                 @String.Format("{0:d}", item.Date)
    33.             </td>
    34.             <td>
    35.                 @String.Format("{0:F}", item.Amount)
    36.             </td>
    37.         </tr>
    38.     
    39.     }
    40.  
    41.     </table>
    42.     <p>
    43.         @Html.ActionLink("Create New Expense", "Create") |
    44.         @Html.ActionLink("Create New Category", "Create","Category")
    45.     </p>

    Index.cshtml

    1. @using MyFinance.Helpers;
    2. @model IEnumerable<MyFinance.Domain.Expense>
    3. @{
    4.     ViewBag.Title = "Index";
    5. }
    6.    <h2>Expense List</h2>
    7.    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    8. <script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
    9. <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script>
    10. <link href="@Url.Content("~/Content/jquery-ui-1.8.6.custom.css")" rel="stylesheet" type="text/css" />
    11.  
    12.    @using (Ajax.BeginForm(new AjaxOptions{ UpdateTargetId="divExpenseList", HttpMethod="Get"})) {
    13.     <table>
    14.         <tr>
    15.         <td>
    16.         <div>
    17.           Start Date: @Html.TextBox("StartDate", Html.Encode(String.Format("{0:mm/dd/yyyy}", ViewData["StartDate"].ToString())), new { @class = "ui-datepicker" })
    18.         </div>
    19.         </td>
    20.         <td><div>
    21.            End Date: @Html.TextBox("EndDate", Html.Encode(String.Format("{0:mm/dd/yyyy}", ViewData["EndDate"].ToString())), new { @class = "ui-datepicker" })
    22.          </div></td>
    23.          <td> <input type="submit" value="Search By TransactionDate" /></td>
    24.         </tr>
    25.     </table>        
    26. }
    27.   <div id="divExpenseList">    
    28.         @Html.Partial("ExpenseList", Model)
    29.     </div>
    30. <script type="text/javascript">
    31.     $().ready(function () {
    32.         $('.ui-datepicker').datepicker({
    33.             dateFormat: 'mm/dd/yy',
    34.             buttonImage: '@Url.Content("~/Content/calendar.gif")',
    35.             buttonImageOnly: true,
    36.             showOn: "button"
    37.         });
    38.     });
    39. </script>

    Ajax search functionality using Ajax.BeginForm


    The search functionality of Index view is providing Ajax functionality using Ajax.BeginForm. The Ajax.BeginForm() method writes an opening <form> tag to the response. You can use this method in a using block. In that case, the method renders the closing </form> tag at the end of the using block and the form is submitted asynchronously by using JavaScript. The search functionality will call the Index Action method and this will return partial view ExpenseList for updating the search result. We want to update the response UI for the Ajax request onto divExpenseList element. So we have specified the UpdateTargetId as "divExpenseList" in the Ajax.BeginForm method.

    Add jQuery DatePicker

    Our search functionality is using a date range so we are providing two date pickers using jQuery datepicker. You need to add reference to the following JavaScript files to working with jQuery datepicker.

    • jquery-ui.js
    • jquery.ui.datepicker.js

    For theme support for datepicker, we can use a customized CSS class. In our example we have used a CSS file “jquery-ui-1.8.6.custom.css”. For more details about the datepicker component, visit jquery UI website at http://jqueryui.com/demos/datepicker . In the jQuery ready event, we have used following JavaScript function to initialize the UI element to show date picker.

    1. <script type="text/javascript">
    2.     $().ready(function () {
    3.         $('.ui-datepicker').datepicker({
    4.             dateFormat: 'mm/dd/yy',
    5.             buttonImage: '@Url.Content("~/Content/calendar.gif")',
    6.             buttonImageOnly: true,
    7.             showOn: "button"
    8.         });
    9.     });
    10. </script>

     

    Source Code

    You can download the source code from http://efmvc.codeplex.com/ .

    Summary

    In this two-part series, we have created a simple web application using ASP.NET MVC 3 RTM, Razor and EF Code First CTP 5. I have demonstrated patterns and practices  such as Dependency Injection, Repository pattern, Unit of Work, ViewModel and Service Layer. My primary objective was to demonstrate different practices and options for developing web apps using ASP.NET MVC 3 and EF Code First. You can implement these approaches in your own way for building web apps using ASP.NET MVC 3. I will refactor this demo app on later time.

  • ASP.NET MVC 3 RTM Released

     The ASP.NET team has released RTM version of ASP.NET MVC 3. You can download the ASP.NET MVC 3 RTM from here and source code of ASP.NET MVC 3 can download from here. Microsoft has released the following products along with ASP.NET MVC 3.

    • NuGet
    • IIS Express 7.5
    • SQL Server Compact Edition 4
    • Web Deploy and Web Farm Framework 2.0
    • Orchard 1.0
    • WebMatrix 1.0

    You can read more details from ScottGu's blog post Announcing release of ASP.NET MVC 3, IIS Express, SQL CE 4, Web Farm Framework, Orchard, WebMatrix .You can upgrade your ASP.NET MVC 2 projects to ASP.NET MVC 3 using MVC 3 Project Upgrade Tool. You can read more details about the MVC 3 Upgrade Tool from here.

    Demo Web App using ASP.NET MVC 3 RTM

     You can download a demo web app using ASP.NET MVC 3 RTM from here. The demo app is explained in the below blog posts

    Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

    Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 2

  • Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1

    In this post, I will demonstrate web application development using ASP. NET MVC 3, Razor and EF code First. This post will also cover Dependency Injection using Unity 2.0 and generic Repository and Unit of Work for EF Code First.You can download the source code from http://efmvc.codeplex.com.The following frameworks will be used for this step by step tutorial.

    1. ASP.NET MVC 3
    2. EF Code First CTP 5
    3. Unity 2.0


    Define Domain Model


    Let’s create domain model for our simple web application

    Category class

    1. public class Category
    2. {
    3.     public int CategoryId { get; set; }
    4.     [Required(ErrorMessage = "Name Required")]
    5.     [StringLength(25, ErrorMessage = "Must be less than 25 characters")]
    6.     public string Name { get; set;}
    7.     public string Description { get; set; }
    8.     public virtual ICollection<Expense> Expenses { get; set; }
    9. }

     

    Expense class

    1. public class Expense
    2. {
    3.        
    4.     public int ExpenseId { get; set; }       
    5.     public string  Transaction { get; set; }
    6.     public DateTime Date { get; set; }
    7.     public double Amount { get; set; }
    8.     public int CategoryId { get; set; }
    9.     public virtual Category Category { get; set; }
    10. }


    We have two domain entities - Category and Expense. A single category contains a list of expense transactions and every expense transaction should have a Category. In this post, we will be focusing on CRUD operations for the entity Category and will be working on the Expense entity with a View Model object in the later post. And the source code for this application will be refactored over time.


    The above entities are very simple POCO (Plain Old CLR Object) classes and the entity Category is decorated with validation attributes in the System.ComponentModel.DataAnnotations namespace. Now we want to use these entities for defining model objects for the Entity Framework 4. Using the Code First approach of Entity Framework, we can first define the entities by simply writing POCO classes without any coupling with any API or database library. This approach lets you focus on domain model which will enable Domain-Driven Development for applications. EF code first support is currently enabled with a separate API that is runs on top of the Entity Framework 4. EF Code First is reached CTP 5 when I am writing this article.


    Creating Context Class for Entity Framework


    We have created our domain model and let’s create a class in order to working with Entity Framework Code First. For this, you have to download EF Code First CTP 5 and add reference to the assembly EntitFramework.dll. You can also use NuGet to download add reference to EEF Code First. 

     

    1. public class MyFinanceContext : DbContext
    2. {
    3.     public MyFinanceContext() : base("MyFinance") { }
    4.     public DbSet<Category> Categories { get; set; }
    5.     public DbSet<Expense> Expenses { get; set; }        
    6. }

     

    The above class MyFinanceContext is derived from DbContext that can connect your model classes to a database. The MyFinanceContext class is mapping our Category and Expense class into database tables
    Categories and Expenses using DbSet<TEntity> where TEntity is any POCO class. When we are running the application at first time, it will automatically create the database. EF code-first look for a connection string in web.config or app.config that has the same name as the dbcontext class. If it is not find any connection string with the convention, it will automatically create database in local SQL Express database by default and the name of the database will be same name as the dbcontext class. You can also define the name of database in constructor of the the dbcontext class.


    Unlike NHibernate, we don’t have to use any XML based mapping files or Fluent interface for mapping between our model and database. The model classes of Code First are working on the basis of conventions and we can also use a fluent API to refine our model. The convention for primary key is ‘Id’ or ‘<class name>Id’.  If primary key properties are detected with type ‘int’, ‘long’ or ‘short’, they will automatically registered as identity columns in the database by default. Primary key detection is not case sensitive. We can define our model classes with validation attributes in the System.ComponentModel.DataAnnotations namespace and it automatically enforces validation rules when a model object is updated or saved.


    Generic Repository for EF Code First


    We have created model classes and dbcontext class. Now we have to create generic repository pattern for data persistence with EF code first. If you don’t know about the repository pattern, checkout Martin Fowler’s article on Repository

    Let’s create a generic repository to working with DbContext and DbSet generics.

    1. public interface IRepository<T> where T : class
    2.     {
    3.         void Add(T entity);
    4.         void Delete(T entity);
    5.         T GetById(long Id);
    6.         IEnumerable<T> All();
    7.     }

     

    RepositoryBasse – Generic Repository class

    1. public abstract class RepositoryBase<T> where T : class
    2. {
    3. private MyFinanceContext database;
    4. private readonly IDbSet<T> dbset;
    5. protected RepositoryBase(IDatabaseFactory databaseFactory)
    6. {
    7.     DatabaseFactory = databaseFactory;
    8.     dbset = Database.Set<T>();
    9. }
    10.  
    11. protected IDatabaseFactory DatabaseFactory
    12. {
    13.     get; private set;
    14. }
    15.  
    16. protected MyFinanceContext Database
    17. {
    18.     get { return database ?? (database = DatabaseFactory.Get()); }
    19. }
    20. public virtual void Add(T entity)
    21. {
    22.     dbset.Add(entity);           
    23. }
    24.       
    25. public virtual void Delete(T entity)
    26. {
    27.     dbset.Remove(entity);
    28. }
    29.  
    30. public virtual T GetById(long id)
    31. {
    32.     return dbset.Find(id);
    33. }
    34.  
    35. public virtual IEnumerable<T> All()
    36. {
    37.     return dbset.ToList();
    38. }
    39. }

     

    DatabaseFactory class

    1. public class DatabaseFactory : Disposable, IDatabaseFactory
    2. {
    3.     private MyFinanceContext database;
    4.     public MyFinanceContext Get()
    5.     {
    6.         return database ?? (database = new MyFinanceContext());
    7.     }
    8.     protected override void DisposeCore()
    9.     {
    10.         if (database != null)
    11.             database.Dispose();
    12.     }
    13. }

    Unit of Work


    If you are new to Unit of Work pattern, checkout Fowler’s article on Unit of Work . According to Martin Fowler, the Unit of Work pattern "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems."


    Let’s create a class for handling Unit of Work

     

    1. public interface IUnitOfWork
    2. {
    3.     void Commit();
    4. }

     

    UniOfWork class

    1. public class UnitOfWork : IUnitOfWork
    2. {
    3.     private readonly IDatabaseFactory databaseFactory;
    4.     private MyFinanceContext dataContext;
    5.  
    6.     public UnitOfWork(IDatabaseFactory databaseFactory)
    7.     {
    8.         this.databaseFactory = databaseFactory;
    9.     }
    10.  
    11.     protected MyFinanceContext DataContext
    12.     {
    13.         get { return dataContext ?? (dataContext = databaseFactory.Get()); }
    14.     }
    15.  
    16.     public void Commit()
    17.     {
    18.         DataContext.Commit();
    19.     }
    20. }

     


    The Commit method of the UnitOfWork will call the commit method of MyFinanceContext class and it will execute the SaveChanges method of DbContext class.
     
    Repository class for Category

    In this post, we will be focusing on the persistence against Category entity and will working on other entities in later post. Let’s create a repository for handling CRUD operations for Category using derive from a generic Repository RepositoryBase<T>.

     

    1. public class CategoryRepository: RepositoryBase<Category>, ICategoryRepository
    2.     {
    3.     public CategoryRepository(IDatabaseFactory databaseFactory)
    4.         : base(databaseFactory)
    5.         {
    6.         }           
    7.     }
    8. public interface ICategoryRepository : IRepository<Category>
    9. {
    10. }


    If we need additional methods than generic repository for the Category, we can define in the CategoryRepository.


    Dependency Injection using Unity 2.0


    If you are new to Inversion of Control/ Dependency Injection or Unity, please have a look on my articles at http://weblogs.asp.net/shijuvarghese/archive/tags/IoC/default.aspx. I want to create a custom lifetime manager for Unity to store container in the current HttpContext.

     

    1. public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
    2. {
    3.     public override object GetValue()
    4.     {
    5.         return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
    6.     }
    7.     public override void RemoveValue()
    8.     {
    9.         HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
    10.     }
    11.     public override void SetValue(object newValue)
    12.     {
    13.         HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
    14.     }
    15.     public void Dispose()
    16.     {
    17.         RemoveValue();
    18.     }
    19. }

     

    Let’s create controller factory for Unity in the ASP.NET MVC 3 application.

    1. public class UnityControllerFactory : DefaultControllerFactory
    2. {
    3. IUnityContainer container;
    4. public UnityControllerFactory(IUnityContainer container)
    5. {
    6.     this.container = container;
    7. }
    8. protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
    9. {
    10.     IController controller;
    11.     if (controllerType == null)
    12.         throw new HttpException(
    13.                 404, String.Format(
    14.                     "The controller for path '{0}' could not be found" +
    15.     "or it does not implement IController.",
    16.                 reqContext.HttpContext.Request.Path));
    17.  
    18.     if (!typeof(IController).IsAssignableFrom(controllerType))
    19.         throw new ArgumentException(
    20.                 string.Format(
    21.                     "Type requested is not a controller: {0}",
    22.                     controllerType.Name),
    23.                     "controllerType");
    24.     try
    25.     {
    26.         controller= container.Resolve(controllerType) as IController;
    27.     }
    28.     catch (Exception ex)
    29.     {
    30.         throw new InvalidOperationException(String.Format(
    31.                                 "Error resolving controller {0}",
    32.                                 controllerType.Name), ex);
    33.     }
    34.     return controller;
    35. }
    36.  
    37. }

     

    Configure contract and concrete types in Unity

    Let’s configure our contract and concrete types in Unity for resolving our dependencies.

     

    1. private void ConfigureUnity()
    2. {
    3.     //Create UnityContainer          
    4.     IUnityContainer container = new UnityContainer()            
    5.     .RegisterType<IDatabaseFactory, DatabaseFactory>(new HttpContextLifetimeManager<IDatabaseFactory>())
    6.     .RegisterType<IUnitOfWork, UnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>())
    7.     .RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>());            
    8.     //Set container for Controller Factory           
    9.     ControllerBuilder.Current.SetControllerFactory(
    10.             new UnityControllerFactory(container));
    11. }

     

    In the above ConfigureUnity method, we are registering our types onto Unity container with custom lifetime manager HttpContextLifetimeManager. Let’s call ConfigureUnity method in the Global.asax.cs for set controller factory for Unity and configuring the types with Unity.

     

    1. protected void Application_Start()
    2. {
    3.     AreaRegistration.RegisterAllAreas();
    4.     RegisterGlobalFilters(GlobalFilters.Filters);
    5.     RegisterRoutes(RouteTable.Routes);
    6.     ConfigureUnity();
    7. }

     

    Developing web application using ASP.NET MVC 3

    We have created our domain model for our web application and also have created repositories and configured dependencies with Unity container. Now we have to create controller classes and views for doing CRUD operations against the Category entity.


    Let’s create controller class for Category

    Category Controller

     

    1. public class CategoryController : Controller
    2. {
    3.     private readonly ICategoryRepository categoryRepository;
    4.     private readonly IUnitOfWork unitOfWork;
    5.  
    6.         public CategoryController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork)
    7.     {
    8.         this.categoryRepository = categoryRepository;
    9.         this.unitOfWork = unitOfWork;
    10.     }  
    11.     public ActionResult Index()
    12.     {
    13.         var categories = categoryRepository.All();
    14.         return View(categories);
    15.     }
    16.     [HttpGet]
    17.     public ActionResult Edit(int id)
    18.     {
    19.         var category = categoryRepository.GetById(id);
    20.         return View(category);
    21.     }
    22.  
    23.     [HttpPost]
    24.     public ActionResult Edit(int id, FormCollection collection)
    25.     {
    26.         var category = categoryRepository.GetById(id);
    27.         if (TryUpdateModel(category))
    28.         {
    29.             unitOfWork.Commit();
    30.             return RedirectToAction("Index");
    31.         }
    32.         else return View(category);            
    33.     }
    34.  
    35.     [HttpGet]
    36.     public ActionResult Create()
    37.     {
    38.         var category = new Category();
    39.         return View(category);
    40.     }
    41.      
    42.     [HttpPost]
    43.     public ActionResult Create(Category category)
    44.     {
    45.         if (!ModelState.IsValid)
    46.         {
    47.             return View("Create", category);
    48.         }            
    49.         categoryRepository.Add(category);
    50.         unitOfWork.Commit();
    51.         return RedirectToAction("Index");
    52.     }
    53.  
    54.     [HttpPost]
    55.     public ActionResult Delete(int  id)
    56.     {
    57.         var category = categoryRepository.GetById(id);
    58.         categoryRepository.Delete(category);
    59.         unitOfWork.Commit();
    60.         var categories = categoryRepository.All();
    61.         return PartialView("CategoryList", categories);
    62.  
    63.     }       
    64. }

     

    Creating Views in Razor

    Now we are going to create views in Razor for our ASP.NET MVC 3 application.  Let’s create a partial view CategoryList.cshtml for listing category information and providing link for Edit and Delete operations.

    CategoryList.cshtml

    1. @using MyFinance.Helpers;
    2. @using MyFinance.Domain;
    3. @model IEnumerable<Category>   
    4.   <table>
    5.         <tr>
    6.         <th>Actions</th>
    7.         <th>Name</th>
    8.          <th>Description</th>
    9.         </tr>
    10.     @foreach (var item in Model) {    
    11.         <tr>
    12.             <td>
    13.                 @Html.ActionLink("Edit", "Edit",new { id = item.CategoryId })
    14.                 @Ajax.ActionLink("Delete", "Delete", new { id = item.CategoryId }, new AjaxOptions { Confirm = "Delete Expense?", HttpMethod = "Post", UpdateTargetId = "divCategoryList" })              
    15.             </td>
    16.             <td>
    17.                 @item.Name
    18.             </td>
    19.             <td>
    20.                 @item.Description
    21.             </td>
    22.         </tr>
    23.     
    24.     }
    25.  
    26.     </table>
    27.     <p>
    28.         @Html.ActionLink("Create New", "Create")
    29.     </p>

    The delete link is providing Ajax functionality using the Ajax.ActionLink. This will call an Ajax request for Delete action method in the CategoryCotroller class. In the Delete action method, it will return Partial View CategoryList after deleting the record. We are using CategoryList view for the Ajax functionality and also for Index view using for displaying list of category information.

    Let’s create Index view using partial view CategoryList 

    Index.chtml

    1. @model IEnumerable<MyFinance.Domain.Category>
    2. @{
    3.     ViewBag.Title = "Index";
    4. }
    5.    <h2>Category List</h2>
    6.    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
    7.    <div id="divCategoryList">          
    8.     @Html.Partial("CategoryList", Model)
    9. </div>

     

    We can call the partial views using Html.Partial helper method. Now we are going to create View pages for insert and update functionality for the Category.

    Both view pages are sharing common user interface for entering the category information. So I want to create an EditorTemplate for the Category information. We have to create the EditorTemplate with the same name of entity object so that we can refer it on view pages using @Html.EditorFor(model => model) . So let’s create template with name Category.

    Category.cshtml

    1. @model MyFinance.Domain.Category
    2. <div class="editor-label">
    3. @Html.LabelFor(model => model.Name)
    4. </div>
    5. <div class="editor-field">
    6. @Html.EditorFor(model => model.Name)
    7. @Html.ValidationMessageFor(model => model.Name)
    8. </div>
    9. <div class="editor-label">
    10. @Html.LabelFor(model => model.Description)
    11. </div>
    12. <div class="editor-field">
    13. @Html.EditorFor(model => model.Description)
    14. @Html.ValidationMessageFor(model => model.Description)
    15. </div>


    Let’s create view page for insert Category information

     

    1. @model MyFinance.Domain.Category
    2.  
    3. @{
    4.     ViewBag.Title = "Save";
    5. }
    6.  
    7. <h2>Create</h2>
    8.  
    9. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    10. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    11.  
    12. @using (Html.BeginForm()) {
    13.     @Html.ValidationSummary(true)
    14.     <fieldset>
    15.         <legend>Category</legend>
    16.                @Html.EditorFor(model => model)      
    17.         <p>
    18.             <input type="submit" value="Create" />
    19.         </p>
    20.     </fieldset>
    21. }
    22.  
    23. <div>
    24.     @Html.ActionLink("Back to List", "Index")
    25. </div>

    ViewStart file


    In Razor views, we can add a file named _viewstart.cshtml in the views directory  and this will be shared among the all views with in the Views directory. The below code in the _viewstart.cshtml, sets the Layout page for every Views in the Views folder.    

    1. @{
    2.     Layout = "~/Views/Shared/_Layout.cshtml";
    3. }

     Source Code

    You can download the source code from http://efmvc.codeplex.com/ . The source will be refactored on over time.

     Summary

    In this post, we have created a simple web application using ASP.NET MVC 3 and EF Code First. We have discussed on technologies and practices such as ASP.NET MVC 3, Razor, EF Code First, Unity 2, generic Repository and Unit of Work. In my later posts, I will modify the application and will be discussed on more things. Stay tuned to my blog  for more posts on step by step application building.

Copyright © 2002-2008 Chennai .Net User Group. All Rights Reserved. Microsoft and Microsoft logo's are trademarks of Microsoft Corporation