DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us today at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Frameworks
  4. Dependency Injection with ASP.NET MVC and Simple Injector

Dependency Injection with ASP.NET MVC and Simple Injector

Jalpesh Vadgama user avatar by
Jalpesh Vadgama
·
Sep. 12, 14 · Interview
Like (0)
Save
Tweet
Share
14.27K Views

Join the DZone community and get the full member experience.

Join For Free

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 Followings 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

ASP.NET MVC ASP.NET Dependency injection

Published at DZone with permission of Jalpesh Vadgama, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • Do Not Forget About Testing!
  • How To Create and Edit Excel XLSX Documents in Java
  • Using the PostgreSQL Pager With MariaDB Xpand

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: