Archives

Archives / 2008 / October
  • ASP.NET MVC Tip: Dependency Injection with Unity Application Block

    In my earlier post, I have explained how to use dependency injection pattern in ASP.net MVC application using StructureMap. In this post, I demonstrate how you can use dependency injection pattern using Microsoft’s Unity Application Block (Unity). If you want to develop an ASP.NET MVC application fully with Microsoft stack, you can use Unity Application Block to perform dependency injection.Unity is a cool dependency injection container and I hope that it will become more powerful in the future releases.

  • ASP.NET MVC for Live Applications

    ASP.NET MVC has got big attention in the community and lot of people are looking to develop production ready applications with ASP.NET MVC. When can we start production ready applications with ASP.NET MVC? Since ASP.NET MVC Beta version is available, I think this is time to start live application with ASP.NET MVC. There is already lot of live applications build with ASP.NET MVC. Stackoverflow is really a killer web application build with ASP.NET MVC.  If you are an Architect, this is the right time to develop infrastructure frameworks for ASP.NET MVC. The RTM version will be in Q4 2008 or Q1 2009. I hope that the RTM version will be release on this December. The changes from Beta to RTM version will be very minimum and the Beta release comes with an explicit "go-live" license that allows you to deploy it in production environments. Scott Guthrie wrote in his bog post ASP.NET MVC Beta Released “Today's ASP.NET MVC Beta release comes with an explicit "go-live" license that allows you to deploy it in production environments.  The previous preview releases also allowed go-live deployments, but did so by not denying permission to deploy as opposed to explicitly granting it (which was a common source of confusion).  Today's release is clearer about this in the license. The beta release is getting close to V1 feature complete, although there are still a few more features that will be added before the final "V1" release (including several VS tooling enhancements).  The team decided to call this release a "beta", though, because the quality and testing of it is higher than the previous previews (a lot of bug fixes and performance tuning work went into it), and they feel that the core features that are in it are now "baked enough" that there won't be major changes from this release to the final product”.

    I believe that breaking changes and new features will be available after the release of V1. When I asked about the SubController infrastructure, Scott Guthrie replied that “The team currently has that penciled in for the release immediately following V1.  The reason for not having it in V1 are: 1) there are a couple of approaches that could be used for it, and we want to spend a little more time investigating and exploring them (and not bake something prematurely into V1), and 2) there is a subcontroller implementation currently in the MVCContrib project that be used with the V1 release.  I'd recommend looking at using that one if you need a subcontroller pattern, and then we'll bake one into the core binary once we feel confident on a final design”.

    Our Development Attitude

    ASP.NET MVC is a great technology and you can build powerful and highly maintainable web applications with ASP.NET MVC. But please keep in mind that you can build good and bad applications with same technology. So our attitude and development approaches are very important for building great software and the most important things is that we should have a good architecture for good software. I strongly believe that the .Net developer community should be more focus on object oriented principles and practices. I believe that the ALT.NET movement is a good sign and the ALT.NET Criterion is good for building better software. The ASP.NET MVC technology is based on a loosely coupled architecture and the framework is highly testable so that it enables to build great software. When we build applications with ASP.NET MVC, we should focus on object-oriented principles and practices and take this time to change our attitude towards object-oriented way. In the past, applications have been data-centric and this has been gradually changing to object-oriented way. I would like to suggest using an ORM for data persistence, Persistence Ignorance (PI) objects for domain layer,  Repository pattern, Inversion of Control (IoC) container for dependency injection (DI) along with your ASP.NET MVC application. And I believe that Test Driven Development (TDD) gives you lot of values to your application development process.

    Learning Resources to start applications

    Stephen Walther’s blog post A Guide to Learning ASP.NET MVC Beta 1 contains lot of links that provides to learn and develop applications with ASP.NET MVC. For validations, Emad Ibrahim’s blog post Client & Server Side Validation in ASP.NET MVC is an excellent one. For dependency injection, my blog post ASP.NET MVC Tip: Dependency Injection with StructureMap provides step by step instructions to apply dependency injection into an ASP.NET MVC application using Structuremap. My blog post ASP.NET MVC Tip: Ajax and Validations using jQuery demonstrates how we can use jQuery for Ajax and validation as well as demonstrating partial rendering using user control. Steve Sanderson's ( Author of Apress' ASP.NET MVC Book) Blog is damn worth to read. And I strongly recommend to visit Rob Conery’s blog for his storefront series.  He has been building an entire ecommerce application with ASP.NET MVC
     

  • ASP.NET MVC Beta Released

    Microsoft has released the official beta for ASP.NET MVC. You can download the Beta version from here.  The Beta installer installs the ASP.NET MVC assemblies (System.Web.Mvc.dll, System.Web.Routing.dll, and System.Web.Abstractions.dll) into the GAC. In previous previews, these were not installed into the GAC. Because of this change, the default project templates do not automatically copy the assembly into the Bin directory of your application.

  • ASP.NET MVC Tip: Dependency Injection with StructureMap

    In this tip, I demonstrate how you can use the dependency injection with StructureMap within an MVC application. StructureMap is an open source Dependency Injection framework for the .NET platform and has been in use since 2004 .StructureMap supports both setter and constructor injection and also offers testing and diagnostic features such as logging, tracing and wiring of mock objects. For download and more details visit http://structuremap.sourceforge.net/default.htm. Jeremy D Miller’s (Creator of StructureMap) blog is a great learning resource for StructureMap and good object oriented programming thoughts.

     

    If you are not familiar with Dependency Injection (DI) and Inversion of Control (IoC), read Martin Fowler’s article Inversion of Control Containers and the Dependency Injection pattern . A Dependency Injection framework injects the dependencies into a class when the dependencies are needed. Dependency Injection enables looser coupling between classes and their dependencies and can be improve architectural qualities of an object oriented business application.

     

    Dependency Injection provides the following advantages,

     

    1) Enables looser coupling between classes and their dependencies

    2) It provides better testability of an application

    3) It removes the need for clients to know about their dependencies and how to   create them.

    4) It avoid behind the problems of creating factory classes, by moving construction responsibility to a framework.

    5) Improve the architecture quality of an object oriented system.

     

    In this tip, I show how you can use the StructureMap to perform Dependency Injection within an ASP.NET MVC application.  In this tip, I will show you how to perform constructor injection. Constructor Injection will push dependencies into a concrete class through constructor arguments.

     

    The below code listings show that a controller class and its dependent classes.

     

     

    Listing 1 – CategoryController

     

    public class CategoryController : Controller {

     ICategoryService  _categoryService = null;

     

     public CategoryController(ICategoryService categoryService) {         

        _categoryService = categoryService;

       }       

     public ActionResult List(int? page) {

      var categories = _categoryService.GetCategories(page ?? 0, 10);

        return View("CategoryList",categories);

      }


     

    Listing 2 – ICategoryService

     

    public interface ICategoryService {

      PagedList<Category> GetCategories(int pageIndex,int pageSize);       

     }

                                   

    Listing 3 – CategoryService

     

    public class CategoryService : ICategoryService  {

     ICategoryRepository _repository = null;       

     public CategoryService(ICategoryRepository repository) {

         _repository = repository;

         if (_repository == null) {

             throw new InvalidOperationException("Repository cannot be null");

            }

    public PagedList<Category> GetCategories(int pageIndex,int pageSize) {

        return _repository.GetCategories().ToPagedList<Category>(pageIndex, pageSize);

            }

        }

     

    Listing 4 – ICategoryRepository

     

    public interface ICategoryRepository {

          IQueryable<Category> GetCategories();

        }

     

    Listing 5 – CategoryRepository

     

    public class CategoryRepository : ICategoryRepository  {

      DBDataContext _db;

      public CategoryRepository(DBDataContext dataContext) {           

         _db = dataContext;           

       }

           

     public IQueryable<Category> GetCategories() {

        return from c in _db.Categories

          select new Category {

            ID=c.ID,

            Name=c.Name,

            Description=c.Description,

            CategoryType = c.CategoryType

          };

         }

        }

     

    Depedencies

     

    The CategoryController has a dependency with ICategoryService. The concrete implementation of ICategoryService, i.e. CategoryService has a dependency with ICategoryRepository. The concrete implementation of ICategoryRepository, i.e. CategoryRepository has a dependency with DBDataContext. When we calling action methods of Category controller, we need to create objects CategoryService, CategoryRepository and DBDataContext.

     

    The below steps will configure StructureMap to perform constructor injection in our ASP.NET MVC application.

     

    Step 1 – Add reference to StructureMap

     

    Add a reference to StructureMap.dll.

    Download available from http://sourceforge.net/projects/structuremap/

     

    Step 2 – Add StructureMap configuration

     

    using StructureMap;

    using StructureMap.Configuration.DSL;

    using StructureMap.Configuration;

    using StructureMap.Pipeline;

     

    public class DomainRegistry : Registry {

       protected override void configure() {

        ForRequestedType<ICategoryService>()

           .TheDefaultIsConcreteType<CategoryService>();

       ForRequestedType<ICategoryRepository>()

          .TheDefaultIsConcreteType<CategoryRepository>();

            }

        }

     

    public class DBServiceRegistry:Registry {

      protected override void configure() {

         ForRequestedType<DBDataContext >()

          .TheDefaultIs(() => new DBDataContext())

            .CacheBy(InstanceScope.Hybrid);

            }

        }

     

    The above configuration tells StructureMap to inject CategoryService when there is a request for ICategoryService. And also inject CategoryRepository when there is a request for ICategoryRepository. The CategoryRepository class has a dependency with Linq DataContext DBDataContext. So we configure that create a new instance DBDataContext when there is request for DBDataContext. we are telling the StructureMapConfiguration to make hybrid instance scope. The below are the different type of instance scoping,

     

       1. PerRequest - The default operation.  A new instance will be created for each request.

       2. Singleton - A single instance will be shared across all requests

       3. ThreadLocal - A single instance will be created for each requesting thread.  Caches the instances with ThreadLocalStorage.

       4. HttpContext - A single instance will be created for each HttpContext.  Caches the instances in the HttpContext.Items collection.

       5. Hybrid - Uses HttpContext storage if it exists, otherwise uses ThreadLocal storage

     

    Step 3 – Register with StructureMap registry

     

    The below code will add instances of DomainRegistry and DBServiceRegistry into StructureMapConfiguration registry.

     

    using StructureMap;

    public static class Bootstrapper {

     public static void ConfigureStructureMap() {

       StructureMapConfiguration.AddRegistry(new DBServiceRegistry());

       StructureMapConfiguration.AddRegistry(new DomainRegistry ());

      }

     }

     

    Step 4 – Controller Factory for StructureMap

     

    using StructureMap;

    public class StructureMapControllerFactory : DefaultControllerFactory {

      protected override IController GetControllerInstance(Type controllerType) {

       try {

          return ObjectFactory.GetInstance(controllerType) as Controller;

        }

    catch (StructureMapException) {

         System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());

          throw;

       }

      }

     

     

    The controller factory is responsible for creating controller instances. We extend the built in default controller factory with our own factory for working StructureMap with ASP.NET MVC .

     

    Step 5 – Modify Global.asax.cs

     

    protected void Application_Start() {

      RegisterRoutes(RouteTable.Routes);

       //Configure StructureMapConfiguration

       Bootstrapper.ConfigureStructureMap();

        //Set current Controller factory as StructureMapControllerFactory

        ControllerBuilder.Current.SetControllerFactory( new myFinance.Web.Controllers.StructureMapControllerFactory()

       );

     }

     

    The above code will set our controller factory and configure StructureMap configuration when our ASP.NET MVC application is started.

     

    Summary

     

    In this tip, I demonstrated how you can use the StructureMap to perform Dependency Injection through constructor injection within an ASP.NET MVC application. One of the greatest advantages of ASP.NET MVC is testability. With a Dependency Injection framework, we can make our ASP.NET MVC application is fully testable and maintainable.


  • ASP.NET MVC Tip: Ajax and Validations using jQuery

    jQuery is now part of the ASP.net development platform and it is going to ship with Visual Studio in the future and will also be the part of ASP.NET MVC installation. ASP.NET MVC will be the first product to include jQuery. Guru Gu’s blog entry has the full details regarding this. This is a great decision from Microsoft and I hope that the community would be happy about the great decision taken by Microsoft. And this is another good step for web development after the ASP.NET MVC technology. jQuery is an excellent java script library and very popular among the web developers regardless of technology. In this post, I demonstrate how to integrate jQuery with ASP.NET MVC and will be explain how to send Ajax requests and also show client side validation using jQuery. I am using a blog application for this demo and it will show how to post a comment of a blog entry using Ajax request and will also show partial rendering with the help of a user control.