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. We want to develop a simple expense tracking application and update expense transactions with a particular expense 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.


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.     T Get(Func<T, Boolean> where);
  7.     IEnumerable<T> GetAll();
  8.     IEnumerable<T> GetMany(Func<T, bool> where);
  9. }

RepositoryBasse – Generic Repository class

  1. public abstract class RepositoryBase<T> where T : class
  2. {
  3.     private MyFinanceContext dataContext;
  4.     private readonly IDbSet<T> dbset;
  5.     protected RepositoryBase(IDatabaseFactory databaseFactory)
  6.     {
  7.         DatabaseFactory = databaseFactory;
  8.         dbset = DataContext.Set<T>();
  9.     }
  10.  
  11.     protected IDatabaseFactory DatabaseFactory
  12.     {
  13.         get; private set;
  14.     }
  15.  
  16.     protected MyFinanceContext DataContext
  17.     {
  18.         get { return dataContext ?? (dataContext = 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> GetAll()
  36.     {
  37.         return dbset.ToList();
  38.     }
  39.     public virtual IEnumerable<T> GetMany(Func<T, bool> where)
  40.     {
  41.         return dbset.Where(where).ToList();
  42.     }
  43.     public T Get(Func<T, Boolean> where)
  44.     {
  45.         return dbset.Where(where).FirstOrDefault<T>();
  46.     }
  47. }

DatabaseFactory class

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

Please note that the generic repository and related classes are just a basic version and will be completely refactored later.

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.

36 Comments

  • Why have you wrapped the DbContext in a class? Can't you just inject the DbContext itself directly into each repository and UnitOfWork via IoC?

  • The generic repository and related classes are basic version and will refactor later

  • Here's the thing,You don't talk about the project's bussiness rules at all that make programming no sense.

  • Hey,I am still reading your article XD,it seems too long to me to finish,lol.
    Anyway,I read the biggest part of this article.I am curious about why you need to build up a DbContext and a DbContextFactory?You have Ioc container XD,it does't need them at all!I hope you will refactor it next time or may be give a better explain reason to me.Don't take it serious!Honestly,it makes people confused,maybe just me!And there is A bigger question is why are you saying people can define the additional methods whatever they want in the Repository constant?I seriously don't agree that.If people have this thought,they should refactor the RepositoryBase not to define some whatever new CRUD method,it will make the Repository dirty.

  • @HuntSoul - Regarding the point for adding new methods in concrete level Reposotories - I mean that you can add specific methods in repository that don't meet the requirement as generic method for RepositoryBase. We can add generic methods in RepositoryBase.

  • you can use conventions in nhibernate too (both fluent NH & conform provide them).

    can you override conventions in EF CF? and if so how?

    its one of the nicest parts of FNH conventions...

  • I liked your article because it's a good basic example of lots of concepts and patterns working together with the latest technologies.

    As the solution develops, I would add a service layer where business logic can live and maybe also show validation using the data objects and some complicated view models with mapping from data objects to DTO's so that clean separation is maintained.

    Looking forward to following this :)

  • I agree with Mick!NHibernate is awesome!

  • hey,Mick,Could you email me?I am interested in what you are talking about,so I am very want to make friends with you.My email adress,saiwolf@163.com
    Expecting to see your email.

  • Are the disposable items stored in HttpContext disposed automatically at the end of the request?

    I have been researching this and I cannot find anything in the Microsoft documentation or in Reflector that indicates that Dispose is called on disposable items in HttpContext.Current.Items at the end of the request. I could be totally missing it though.

    I set a breakpoint on Disposable.Dispose in your example and it was never called. I set a breakpoint on the finalizer in Disposable and forced garbage collection using the code below in the Edit action of the CategoryController to see if I could catch the Garbage Collector cleaning up the DatabaseFactory that was created for the Index action of the CategoryController. I did catch it.
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();


    If it is true that the disposable objects in HttpContext.Current.Items are not disposed of at the end of a request, I was trying to create a solution to this.

    One option is to handle the Application_EndRequest Global.asax and either dispose any IDisposable type:

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
    foreach (var item in
    HttpContext.Current.Items.OfType()
    .Where(item => item.Value is IDisposable))
    {
    ((IDisposable)item.Value).Dispose();
    }
    }

    or explicitly dispose the HttpContextLifetimeManager for the type:
    protected void Application_EndRequest(Object sender, EventArgs e)
    {
    (new HttpContextLifetimeManager()).Dispose();
    }

    I may be totally missing the point on this. I would appreciate any guidance your have. I enjoyed your article.

  • Hi Shiju. This is great. Is there any chance you can give a brief explanation of the role that each of the classes has (DatabaseFactory, Disposable, RepositoryBase, UnitOfWork and MyFinanceContext) and the advantages of this approach please?



  • How is this a generic repository when I have to create a new Repository class for every "model" I want to save to the database. Is it possible to use RepositoryBase directly?

  • @Amir - RepositoryBase is a abstract class and can't use it directly. You need to create concrete level Repository classes. In real world apps, you may need to add additional methods into the concrete level Repository classes.

  • That's the best basic MVC + Entity Framework project I've ever seen.
    Thanks!

    Where to read next parts?

  • Why are you using a separate UnitOfWork class? Isn't the DbContext a UnitOfWork on it's own? So is it also a solution to add the commit method to the BaseRepository and remove the UnitOfWork class? Thanks for you answer!

  • @M@@N - I don't like to use commit methods in repository class and want to implement Unit Of Work as a separate responsibility. A group of transactions may be use multiple repository classes and want to co-ordinate the transaction using a Unit of Work class.

  • Shiju, please can you explain why you override DefaultControllerFactory instead of overriding IControllerActivator?

    If my understanding is correct, in MVC 3 RTM you only need to override IControllerActivator.

    Also, what was your reasoning behind creating an HttpContextLifetimeManager as opposed to creating child Unity containers for each request? What are the pros and cons in your opinion?

    Thanks

  • @Daniel - Thanks for point out the IControllerActivator. The existing implementation was compatible with MVC 2. You can use this with ASP.NET MVC 3 and recommending over the existing implementation. I have updated the source code repository with DependencyResolver class and the IControllerActivator. You can download it from http://efmvc.codeplex.com/

    I want to use a custom HttpContextLifetimeManager class for managing the lifetime of the container with every Http request Context.

  • This has been really, really helpful. Thank you for spending the time to post!

  • Thanks for that sample, which combines a lot of useful patterns!
    Could you explain the reason for the DatabaseFactory? Why not passing the MyFinanceContext (DbContext) to the constructor of a repository class?

    Thx!

  • where fits ExecuteQuery or ExecuteStoredProcedure on this approach to not break the Unity, and Repository ideas. for example there are applications with Complex query selects, so in this example for exmple how to run a complex query from Expenses repository with .ExecuteQuery()

  • @jlserrano - You can add a method contract in IExpensesRepository interface and add its implementation in its concrete class for executing complex query. Since DbContext doesn't provide support for mapping stored procedures, you can call procedure/Complex query directly by using context.Database.SqlCommand() or context.Database.SqlQuery().This implementation will not break any existing implementations.

  • @Shiju, how would I implement the UoW without the DatabaseFactory, rather, using DI/IoC?

  • I'm trying to follow along, but I get stuck because when I try to call ConfigureUnity() from Application_Start() it complains first about the method being private, so I change it to public. Then I get an error saying, 'An object reference is required for the non-static field, method, or property 'FinanceApp.Models.Unity.UnityControllerFactory.ConfigureUnity()'.

    The link to the source code seems to be the 'refactored' code, is it possible to post a link to the original source code?

  • Hi Shiju,
    Confused on how I can write a select with only a few columns using the repository pattern rather than retrieving all the columns. Any ideas?

  • Shiju, when you do a getall() on category, it also gets the expenses of those categories along with it, what if I don't need to show the expenses, is there something I can use to get just the categories and not the included expenses - tx


  • Why fo;;owing line commented in the code of Global.asax.cs file

    //.RegisterType() // No nned to a controller activator

    Still everything work fine.

    Even if i exclude file UnityControllerFactory.cs from the project everything works fine.

    Please clarify this

    Thanks
    Shahj

  • @shahj
    The UnityControllerFactory have used before MVC 3 versions and current code block is enough to perform DI using Unity

  • Is there a way to release all resource at the end of the application or if the browser has been closed by the user

  • You have interface IRepository as well as abstract class RepositoryBase, why this is required can we just not use interface IRepository

  • @Jignesh Shah - IRepository contains the contract for generic methods and RepositoryBase contains generic implementation of commonly used methods.

  • Realy Realy Thanks for your useful article!!

  • "Login failed for user 'DangBinh876'. Reason: The account is disabled." (Error: When i disabled account my computer in SQL Server 2008 R2), so i want change connectionstring (Use account sa in SQL Server 2008 R2, or Connect Database of computer other).
    But i see ConnectionString in web.config don't agency (after download source, i remove ConnectString >> App Run Success).

    How use ConnectionString in web.config file >> to "MyFinanceContext" .
    " public class MyFinanceContext : DbContext
    {
    public MyFinanceContext() : base("MyFinance") { }
    ....
    }
    "
    Please help me, thanks so much!
    binhnd@uyvien.vn

  • "I want to use a custom HttpContextLifetimeManager class for managing the lifetime of the container with every Http request Context."

    I did not understand the role of UnityControllerFactory or HttpContextLifetimeManager. Could anyone explains to me why I need to create this classes?

  • Why didn't you inject DataContext in UnitOfWork instead of injecting the DatabaseFactory?

    It feels better if you remove the dependency of UnitOfWork to DatabaseFactory, the Repositories and UnitOfWork should point to the same DataCnotext in an HttpRequest.

  • This blog is not suitable for newbie persons which they are try to learn mvc 3.0.... please try to explain little small amount of examples...

Comments have been disabled for this content.