How to use StructureMap to inject repository classes to the controller?
Posted
by
Lorenzo
on Stack Overflow
See other posts from Stack Overflow
or by Lorenzo
Published on 2011-01-16T00:08:50Z
Indexed on
2011/01/16
2:53 UTC
Read the original article
Hit count: 214
In the current application I am working on I have a custom ControllerFactory class that create a controller and automatically sets the Elmah ErrorHandler.
public class BaseControllerFactory : DefaultControllerFactory
{
public override IController CreateController( RequestContext requestContext, string controllerName ) {
var controller = base.CreateController( requestContext, controllerName );
var c = controller as Controller;
if ( c != null ) {
c.ActionInvoker = new ErrorHandlingActionInvoker( new HandleErrorWithElmahAttribute() );
}
return controller;
}
protected override IController GetControllerInstance( RequestContext requestContext, Type controllerType ) {
try {
if ( ( requestContext == null ) || ( controllerType == null ) )
return base.GetControllerInstance( requestContext, controllerType );
return (Controller)ObjectFactory.GetInstance( controllerType );
}
catch ( StructureMapException ) {
System.Diagnostics.Debug.WriteLine( ObjectFactory.WhatDoIHave() );
throw new Exception( ObjectFactory.WhatDoIHave() );
}
}
}
I would like to use StructureMap to inject some code in my controllers. For example I would like to automatically inject repository classes in them.
I have already created my repository classes and also I have added a constructor to the controller that receive the repository class
public FirmController( IContactRepository contactRepository ) {
_contactRepository = contactRepository;
}
I have then registered the type within StructureMap
ObjectFactory.Initialize( x => {
x.For<IContactRepository>().Use<MyContactRepository>();
});
How should I change the code in the CreateController method to have the IContactRepository
concrete class injected in the FirmController
?
EDIT:
I have changed the BaseControllerFactory to use Structuremap. But I get an exception on the line
return (Controller)ObjectFactory.GetInstance( controllerType );
Any hint?
© Stack Overflow or respective owner