Resolving Dependencies in ASP.NET MVC 5 using Unity Container

In this post, I will show you how to use Unity Container in ASP.NET MVC 5 application. This post may be handy for you because the way Unity was used in MVC 4 has been changed in MVC 5. Assuming you already have ASP.NET MVC 5 application, you can start using Unity Container using Nuget. Right click on project and from context menu click on Manage Nuget Packages and search for Unity.mvc5. Click to install Unity.mvc5 package in ASP.NET MVC application.

clip_image002

In App_Start folder you will find UnityConfig.cs. UnityConfig is a static class with one static method RegisterComponents. In this method you need to register dependency. For example ASP.NET MVC 5 application I am working on, got MovieRepository class depended on IMovieRepository. You need to instruct unity that IMovieRepository should resolve to MovieRepository. You can do this by registering type in Unity Container. [See image below]

clip_image004

If you have more than one dependencies all should get registered to container in RegisterComponents function. After registering all dependencies call RegisterComponents function in Application_Start() of Global.asax.cs . This can be done as shown below,

clip_image006

Note:

In earlier version of ASP.NET MVC and UNITY, you might have seen BootStrapper.start(). In MVC 5 it has been changed to UnityConfig.RegisterComponents()

In Controller class now I can inject dependency simply as below,

clip_image008

This is what all you need to do to resolve dependency using Unity Container in ASP.NET MVC application. In further posts I will discuss how to use other IOC containers like Structuremap, Windsor etc.

Happy Coding.

Day #2: Learn ASP.NET MVC 5- Adding View

Day #1: Learn ASP.NET MVC 5- Adding Controller

On Day1 we learnt about Adding Controller. Today we will learn to add View in MVC project. Let us start with understanding with is View?

View is part of MVC that renders user interface. View contains markup that gets render with ViewEngines. ViewEngines generates View in ASP.NET MVC framework. There are two kinds of View Engines. One is aspx engine and other Razor engine.

We can say View is User Interface in MVC application and it never talks to database or model directly. It does not contain any business or application logic. Controller returns a View to be rendered.

image

You can add a View, right click on Product subfolder and select Add from context menu and then select template MVC 5 View Page with Layout.

image

There are four options for Views.

  1. MVC 5 View Page
  2. MVC 5 View Page with Layout
  3. MVC 5 Layout Page
  4. MVC5 Partial Page

Let us start with adding a MVC5 View Page with Layout. Give name of the View as of the action name. For example, if we have action in controller as below,


  public ActionResult Index()
        {
            return View();
        }

Then we will create a View with name Index since action name is Index and it is returning view. Next we need to select layout page. Let us go ahead and select a Layout.cshtml from Shared folder.

image

After adding View, you will find that inside Views->Product folder index.cshtml being added.

image

By default following code gets created in Index view

image

Let us explore above code line by line,

  • We are setting layout of view as _Layout.cshtml from Shared folder.
  • ViewBag is used to pass parameters. We are setting Title of the View as Index.
  • On DOM creating some HTML elements like <h2> and <p>

Now let us go ahead and run application. On navigating Index action in Product controller, you will get index view rendered in browser.

image

Let us go ahead and explore _Layout.cshtml. We are passing title from View to layout using ViewBag.

image

On running application, you may notice that browser title is set to Index-My ASP.NET Application. On further exploring _Layout.cshtml, you will find navigation links and footer. If required you can change content of layout as well.

Next let us see how we can pass data from Controller to a View. Before we go into demo section, let us understand that View will never interact with Model directly and perform any business logic. Controller will talk to Model and perform business operation on data and then pass that to View to get rendered.

image

Some of the important points are as follows,

  1. View never perform business logic
  2. View never interacts with Model
  3. Controller talk to Model , performs business logic and pass data to View

So let us say we want to pass data from Controller to View. Controller got an Action named Data as below,


    public ActionResult Data(string fruit, int eatingtimes)
        {
            ViewBag.fruit = fruit;
            ViewBag.times = eatingtimes;
            return View();

        }

From Data action, we are passing fruit and times as parameter from Controller to View. We are using ViewBag property to pass data from Controller to View. Now these passed data can be used on View as below. We have created a View named data without any layout.


 <div>
        <h2>Data</h2>
        <ul>
            @for (int i = 0; i < ViewBag.times; i++)
            {
                <li>@ViewBag.fruit</li>
            }
        </ul>

    </div>

In Route we have added a new Route as below,


  routes.MapRoute(
               name: "Product",
               url: "{controller}/{action}/{fruit}/{eatingtimes}"
           );

Let us go ahead and run application. We are passing mango as fruit and 9 as eatingtimes. As a output Mango will get render 9 times on View.

image

This is the way you can pass parameters from Controller to View. In further posts, we will complexity around Views and working with different kind of Views. I hope you find this post useful. Thanks for reading.

Day #1: Learn ASP.NET MVC 5- Adding Controller

 

After long time, I am back to web development. At current web development paradigm, ASP.NET MVC framework is one of the most popular and heavily used web development framework. Seeing popularity and usefulness of ASP.NET MVC, I have decided to write easy to go blog series on this. In this blog post series, each day I will share my learning in form of blog posts.

In day 1, let us learn about Controller. Very first in simpler words,

“Controller does all the actions in MVC. It handles user interactions or inputs. It passes users’ data to Model and selects a View to render on UI”

image

In more coding terms, Controller can be define as below,

  1. Controller is a class
  2. It contains one or more methods called Actions
  3. An Action can return simple string or a selected View to UI
  4. Action takes all browser requests or user inputs
  5. It retrieves data from Model
  6. It selects View to be rendered on UI

You can add a controller by right clicking on Controllers folder in solution explorer. In context menu select Add->Controller. There are different types of Controller templates are available to add. Let us go ahead and select MVC 5 Controller- Empty template to add controller.

image

Next give name to Controller. I am giving name as ProductController.

image

In solution explorer, you will notice In Controller folder, ProductController.cs file being added and in Views folder, there is subfolder Product being added.

image

Next let us go ahead and remove default code created and following two actions. First Action is Index (It is default) action. Index action does not take any input parameter. Second Action added is Welcome. It takes two input parameters id and name.

 


public class ProductController : Controller
{
//
// GET: /Product/
public string Index()
{
return "this is default action";
}

public string Welcome(string name, int id)
{
return "this is welcome action" + name + "with id " + id;
}
}

Following points are worth noticing about ProductController.

  1. ProductController class extends Controller class
  2. Actions are created as methods.
  3. In this case Actions are returning string.
  4. Actions can return other types as well. We will discuss them in further posts.
  5. Actions can take zero or more input parameter.

Let us go ahead and run application. Default action of Product controller is index. On navigating Product Controller, Index action will be called. In this case Index action is returning a string.

clip_image002

We have put one more action Welcome in Product controller. This takes two input parameters Id and name. You can call Welcome action as below. We are passing two input parameters as query string.

image

Better approach to pass input parameters are as Route Data than query string. Id is default input parameter. So instead of passing id as query string, you can pass it as route data as well.

clip_image002[6]

You can find default route and parameters in RouteConfig.cs.

 

clip_image003

 

In above code as you see default controller is Home, default action is Index and default optional parameter is id. If you want to pass other input parameters as route option, you can very much do that by adding more routes.

clip_image005

We have added a route with name and id as parameter. On running application, now you can pass name and id as route option.

clip_image007

This is the basic of working with Controllers in MVC. In further posts we will get into deeper concepts of Controllers. I hope you find this post useful. Thanks for reading.