29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Listing 19-5. The IControllerFactory Interface<br />

using System.Web.Routing;<br />

using System.Web.SessionState;<br />

namespace System.Web.Mvc {<br />

public interface IControllerFactory {<br />

IController CreateController(RequestContext requestContext,<br />

string controllerName);<br />

SessionStateBehavior GetControllerSessionBehavior(RequestContext<br />

requestContext,<br />

string controllerName);<br />

}<br />

}<br />

void ReleaseController(IController controller);<br />

In the sections that follow, I create a simple custom controller factory and walk you through implementations for each of the<br />

methods in the IControllerFactory interface. To begin, I created an Infrastructure folder and added a new<br />

class file called CustomControllerFactory.cs, which I used to create the custom controller factory shown in<br />

Listing 19-6.<br />

Listing 19-6. The Contents of the CustomControllerFactory.cs File<br />

using System;<br />

using System.Web.Mvc;<br />

using System.Web.Routing;<br />

using System.Web.SessionState;<br />

using ControllerExtensibility.Controllers;<br />

namespace ControllerExtensibility.Infrastructure {<br />

public class CustomControllerFactory: IControllerFactory {<br />

public IController CreateController(RequestContext requestContext,<br />

string controllerName) {<br />

"Product";<br />

Type targetType = null;<br />

switch (controllerName) {<br />

case "Product":<br />

targetType = typeof(ProductController);<br />

break;<br />

case "Customer":<br />

targetType = typeof(CustomerController);<br />

break;<br />

default:<br />

requestContext.RouteData.Values["controller"] =<br />

}<br />

targetType = typeof(ProductController);<br />

break;<br />

return targetType == null ? null :<br />

(IController)DependencyResolver.Current.GetService(targetType);<br />

505

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!