This document discusses using the Castle Windsor Inversion of Control (IoC) container to configure dependencies in an MVC application. It describes registering components with Windsor, including controllers, data storage, and a media library. It also covers refactoring from hard dependencies to using a factory interface to resolve movie objects, implementing the factory, and configuring it in Windsor. The goal is to decouple components and make the code more testable.
Ten Organizational Design Models to align structure and operations to busines...
Using Castle Windsor to implement Inversion of Control and Dependency Injection in an ASP.NET MVC application
1. AMIR BARYLKO
IOC INTRO II
Using Castle Windsor
Anvil Digital Aug 2010
Tuesday, August 17, 2010
2. WINDSOR TESTS
• Register and Retrieve
• Register a particular instance
• Register Transient
• Constructor resolution
• Retrieve with parameters
• Retrieve instance by name
• Retrieve all instances
Tuesday, August 17, 2010
3. ADD WINDSOR CONFIG
• Modify Global.asax
• // Setup IoC container
• this.SetupContainer();
• // Register the factory for the controllers
• ControllerBuilder.Current.SetControllerFactory(new
WindsorControllerFactory(this.Container));
Tuesday, August 17, 2010
4. CONFIGURE WINDSOR
• private void SetupContainer()
• {
• this.Container = new WindsorContainer();
• // add more configuration here
• }
Tuesday, August 17, 2010
5. ADD CONTROLLERS
• Use Name to identify them
• They have to be transient
• Component.For<MoviesController>().Named
("MoviesController").LifeStyle.Transient,
• Component.For<HomeController>().Named
("HomeController").LifeStyle.Transient,
Tuesday, August 17, 2010
8. REFACTORING HARD
DEPENDENCIES
• MoviesController
• Hard dependency from MoviesController to create a movie
• public ActionResult Create(string title)
•{
• this._library.Add(new Movie { Title = title });
• return Redirect("Index");
•}
Tuesday, August 17, 2010
9. MOVIE FACTORY
• Create class to handle movie creation
• public interface IMovieFactory
• {
• IMovie Create(string title);
• }
Tuesday, August 17, 2010
10. MOVIES CONTROLLER
• Write test
• Inject factory in the constructor
• Change creation by using the factory
• [AcceptVerbs(HttpVerbs.Post)]
• public ActionResult Create(string title)
• {
• this._library.Add(this._factory.Create(title));
• return Redirect("Index");
• }
Tuesday, August 17, 2010