NHibernate configuration is no different to a Spring.Net webforms app. Add the OpenSessionInView
module to web.config
and define a session factory named SessionFactory
in the spring config.
Spring.Net and MVC integration is done by registering a custom IControllerFactory
in application startup, this applies a custom ControllerActionInvoker
. The controller factory creates or configures controllers and the action invoker configures any ActionFilter
.
public class MvcApplication: System.Web.HttpApplication
{
public static void RegisterRoutes( RouteCollection routes )
{
//
}
protected void Application_Start()
{
RegisterRoutes( RouteTable.Routes );
lock (this) {
ControllerBuilder.Current.SetControllerFactory( new SpringControllerFactory() );
}
}
}
public class SpringControllerFactory: DefaultControllerFactory
{
public SpringControllerFactory()
{
SpringContext = WebApplicationContext.Current;
}
protected override IController GetControllerInstance( Type controllerType )
{
IController controller = null;
if (SpringContext.ContainsObject( controllerType.Name )) {
controller = (IController) SpringContext.GetObject( controllerType.Name );
}
if (controller == null) {
controller = base.GetControllerInstance( controllerType );
SpringContext.ConfigureObject( controller, controllerType.FullName );
}
var standardController = controller as Controller;
if (standardController != null) {
standardController.ActionInvoker = new SpringActionInvoker();
}
return controller;
}
private IApplicationContext SpringContext
{ get; set; }
}
public class SpringActionInvoker: ControllerActionInvoker
{
public SpringActionInvoker()
{
SpringContext = WebApplicationContext.Current;
}
protected override FilterInfo GetFilters( ControllerContext controllerContext, ActionDescriptor actionDescriptor )
{
var filterInfo = base.GetFilters( controllerContext, actionDescriptor );
foreach (IActionFilter filter in filterInfo.ActionFilters.Where( f => f != null )) {
SpringContext.ConfigureObject( filter, filter.GetType().FullName );
}
foreach (IAuthorizationFilter filter in filterInfo.AuthorizationFilters.Where( f => f != null )) {
SpringContext.ConfigureObject( filter, filter.GetType().FullName );
}
foreach (IExceptionFilter filter in filterInfo.ExceptionFilters.Where( f => f != null )) {
SpringContext.ConfigureObject( filter, filter.GetType().FullName );
}
foreach (IResultFilter filter in filterInfo.ResultFilters.Where( f => f != null )) {
SpringContext.ConfigureObject( filter, filter.GetType().FullName );
}
return filterInfo;
}
private IApplicationContext SpringContext
{ get; set; }
}
Mvc Contrib has a similar SpringControllerFactory, though it does not configure action filters. It is configured in application startup:
protected void Application_Start()
{
RegisterRoutes( RouteTable.Routes );
lock (this) {
ControllerBuilder.Current.SetControllerFactory( new SpringControllerFactory() );
SpringControllerFactory.Configure( WebApplicationContext.Current );
}
}