I keep needing this so thought I would put is somewhere:
in MVC you are given a very nice Url.Content element which allows you to build a site to the url with a tilde ~.
There is an equivalent in ASP.NET: Page ResolveUrl()
Wednesday, 20 February 2013
Friday, 25 January 2013
MVC4 StrucutureMap ControllerFactory
I am not sure if this is new to MVC4 only, but it does appear that Dependency Injection with MVC just got easier. This code is borrowed, and referenced here so I don't have to keep going off and finding it.
First off I create a ControllerFactory for StrucutureMap
public class StructureMapControllerFactory : DefaultControllerFactory { public IContainer Container { get; set; } public StructureMapControllerFactory() { Container = ObjectFactory.Container; } protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { IController controller; if (controllerType == null) { throw new HttpException(404, String.Format(Resources.ControllerNotFound, requestContext.HttpContext.Request.Path)); } if (!typeof(IController).IsAssignableFrom((controllerType))) { throw new ArgumentException(string.Format(Resources.NotAController, controllerType.Name),"controllerType"); } try { controller = Container.GetInstance(controllerType) as Controller; } catch (Exception ex) { throw new InvalidOperationException(string.Format(Resources.UnableToResolveController, controllerType.Name),ex); } return controller; } }
Then in the Global.asax Application_Start method.
Add the setup for StructureMap, I tend to do all that in a separate class:
DependencyInjection.StructureMap.Initialise();
And then set the ControllerFactory to your new custom factory:
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
Labels:
C#,
ControllerFactory,
Dependency Injection,
MVC4,
StructureMap
Subscribe to:
Posts (Atom)