How to use StructureMap to inject repository classes to the controller?
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.开发者_Go百科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?
Before typing in the solution, I would recommend using the Container type to initialize SM rather than ObjectFactory
The best way to accomplish this would be to have a class subclassed from the Registry class in StructureMap framework. so, my Registry would be something like
public class MyAppRegistry : Registry
{
public MyAppRegistry()
{
For<IContactRepository>().Use<MyContactRepository>();
}
}
and then tell SM to use this Registry during configuration.
var container = new Container(x=>x.AddRegistry(new MyAppRegistry());
this would be done from the Application_Start in the Global.asax. After the above line, set the ControllerBuilder in mvc to use the BaseControllerFactory. Now SM should be able to resolve all dependencies
精彩评论