Skip to main content

Dependency Injection with ASP.NET MVC and Simple Injector


I have been learning SimpleInjector for few days and it’s just awesome.  I have already written two post about it(see below link) and this post will be third post about it. In this post we are going to learn how we can do Dependency Injection with ASP.NET MVC.

For those who are reading my posts about Simple Injector Following are two previous post I have written about Simple Injector. I highly recommend to read first two post so that you can be aware about how we can configure SimpleInjector container.

Dependency Injection with Simple Injector
Singleton Instance in Simple Injector

So let’s start with creating a ASP.NET MVC Project from Visual Studio.



There is already nuget package created for ASP.NET MVC Integration available so you can install that via following nuget command.
Install-Package SimpleInjector.Integration.Web.Mvc 

simple-injector-asp-net-mvc-nuget-integration-package

Now I have created a following model class called customer.
namespace MVCDISimpleInjector.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Now let’s write a repository interface and repository class for the Customer Model Class.
using System.Collections.Generic;

namespace MVCDISimpleInjector.Models
{
    public interface ICustomerRepository
    {
        List<Customer> GetCustomers();
    }
}
Here is a implementation of ICustomerRepository interface.
using System.Collections.Generic;

namespace MVCDISimpleInjector.Models
{
    class CustomerRepository : ICustomerRepository
    {
        public List<Customer> GetCustomers()
        {
            var customers = new List<Customer>
            {
                new Customer{Id=1,FirstName = "Jalpesh", LastName = "Vadgama"},
                new Customer{Id=2,FirstName = "Vishal",LastName = "Vadgama"}
            };
            return customers;
        }
    }
}
Here I have only created a static list of Customers as purpose of this post to show dependency injection with ASP.NET MVC.  Let’s create a controller for customer via right click on controller folder and add new –> Controller.
using System.Web.Mvc;
using MVCDISimpleInjector.Models;

namespace MVCDISimpleInjector.Controllers
{
    public class CustomerController : Controller
    {
        private ICustomerRepository _customerRepository;

        public CustomerController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }

        // GET: Customer
        public ActionResult Index()
        {
            var customer = _customerRepository.GetCustomers();
            return View(customer);
        }
    }
}
Here I have used only Index Action result as purpose of this post to show dependency injection with ASP.NET MVC and SimpleInejctor.

Let’s add a new view for customer via right click on View in Index ActionResult in Customer Controller.

add-view-simple-injector

Now let’s run this. It will give error

parameter-less-constructor-asp-net-mvc

It’s because ASP.NET MVC by default only parameter less constructor and we have already added a parameter in Customer Controller. So it’s time to write a code for that.

I have written a following code in Application_Start event for doing injection for controller.
using System.Reflection;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using MVCDISimpleInjector.Models;
using SimpleInjector;
using SimpleInjector.Integration.Web.Mvc;

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

            //Code for registering our repository class and DI
            var container = new Container();
            container.Register<ICustomerRepository, CustomerRepository>();

            // This two extension method from integration package
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            DependencyResolver.SetResolver(
                new SimpleInjectorDependencyResolver(container));
        }
    }
}
Here if you see the code carefully First I have created a object of Simple Injector container and then I have registered Customer Repository classes and interface. So whenever you request ICustomerRespotiroy object it will crate CustomerRepository class object. Then I have used “ResgisterMVCControllers” method which register all controllers in current executing assembly.  At last I have set MVC dependency resolver to Simple Injector Dependency Resolver with container as parameter so that it will resolve all dependencies for controller.

Now let's run again and it’s working.

depedency-injection-with-simple-injector-asp-net-mvc

It’s very easy with Simple Injector integration Nuget Pacakge. Hope you like it. Stay tuned for more!
You can find complete source code of this application on github at https://github.com/dotnetjalps/MVCDISimpleInjector

Comments

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command How to solve : gulp is not recognized as internal or external command To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.



Go to Advance System Settings and it will open system properties windows like below.



Click on Environment Variables it will open an environment and system variables windows like below.



Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.



Click on Ok. That’s it. N…