Skip to content

Instantly share code, notes, and snippets.

Created October 4, 2011 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1262927 to your computer and use it in GitHub Desktop.
Save anonymous/1262927 to your computer and use it in GitHub Desktop.
Inject into ActionFilter
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Spring.Context;
using Spring.Context.Support;
namespace SpringActionFilterSample
{
/// <summary>
/// Spring.NET-specific HttpApplication for ASP.NET MVC integration.
/// </summary>
public abstract class SpringMvcApplication : HttpApplication
{
/// <summary>
/// Executes custom initialization code after all event handler modules have been added.
/// </summary>
public override void Init()
{
base.Init();
//the Spring HTTP Module won't have built the context for us until now so we have to delay until the init
ConfigureApplicationContext();
}
/// <summary>
/// Handles the BeginRequest event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void Application_BeginRequest(object sender, EventArgs e)
{
var resolver = BuildDependencyResolver();
RegisterDependencyResolver(resolver);
}
/// <summary>
/// Builds the dependency resolver.
/// </summary>
/// <returns>The <see cref="IDependencyResolver"/> instance.</returns>
/// You must override this method in a derived class to control the manner in which the
/// <see cref="IDependencyResolver"/> is created.
protected virtual IDependencyResolver BuildDependencyResolver()
{
return new SpringMvcDependencyResolver(ContextRegistry.GetContext());
}
/// <summary>
/// Configures the <see cref="Spring.Context.IApplicationContext"/> instance.
/// </summary>
/// <remarks>
/// You must override this method in a derived class to control the manner in which the
/// <see cref="Spring.Context.IApplicationContext"/> is configured.
/// </remarks>
protected virtual void ConfigureApplicationContext()
{
}
/// <summary>
/// Registers the DependencyResolver implementation with the MVC runtime.
/// <remarks>
/// You must override this method in a derived class to control the manner in which the
/// <see cref="SpringMvcDependencyResolver"/> is registered.
/// </remarks>
/// </summary>
public virtual void RegisterDependencyResolver(IDependencyResolver resolver)
{
ThreadSafeDependencyResolverRegistrar.Register(resolver);
}
/// <summary>
/// Thread-safe class that ensures that the <see cref="IDependencyResolver"/> is registered only once.
/// </summary>
protected static class ThreadSafeDependencyResolverRegistrar
{
private static bool _isInitialized = false;
private static readonly Object @lock = new Object();
/// <summary>
/// Registers the specified resolver.
/// </summary>
/// <param name="resolver">The resolver.</param>
public static void Register(IDependencyResolver resolver)
{
if (_isInitialized)
{
return;
}
lock (@lock)
{
if (_isInitialized)
{
return;
}
DependencyResolver.SetResolver(resolver);
_isInitialized = true;
}
}
}
}
/// <summary>
/// Spring-based implementation of the <see cref="IDependencyResolver"/> interface.
/// </summary>
public class SpringMvcDependencyResolver : IDependencyResolver
{
private IApplicationContext _context;
/// <summary>
/// Initializes a new instance of the <see cref="SpringMvcDependencyResolver"/> class.
/// </summary>
/// <param name="context">The context.</param>
public SpringMvcDependencyResolver(IApplicationContext context)
{
_context = context;
}
/// <summary>
/// Gets the application context.
/// </summary>
/// <value>The application context.</value>
public IApplicationContext ApplicationContext
{
get
{
if (_context == null || _context.Name != ApplicationContextName)
{
if (string.IsNullOrEmpty(ApplicationContextName))
{
_context = ContextRegistry.GetContext();
}
else
{
_context = ContextRegistry.GetContext(ApplicationContextName);
}
}
return _context;
}
}
/// <summary>
/// Gets or sets the name of the application context.
/// </summary>
/// <remarks>
/// Defaults to using the root (default) Application Context.
/// </remarks>
/// <value>The name of the application context.</value>
public static string ApplicationContextName { get; set; }
/// <summary>
/// Resolves singly registered services that support arbitrary object creation.
/// </summary>
/// <param name="serviceType">The type of the requested service or object.</param>
/// <returns>The requested service or object.</returns>
public object GetService(Type serviceType)
{
object service = null;
if (serviceType != null)
{
var services = ApplicationContext.GetObjectsOfType(serviceType);
if (services.Count > 0)
{
service = services.Cast<DictionaryEntry>().First().Value;
}
}
return service;
}
/// <summary>
/// Resolves multiply registered services.
/// </summary>
/// <param name="serviceType">The type of the requested services.</param>
/// <returns>The requested services.</returns>
public IEnumerable<object> GetServices(Type serviceType)
{
var services = ApplicationContext.GetObjectsOfType(serviceType);
return services.Values.Cast<object>();
}
}
public class FilterProvider : FilterAttributeFilterProvider, IApplicationContextAware
{
public IApplicationContext ApplicationContext
{
set;
get;
}
public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
var filters = base.GetFilters(controllerContext, actionDescriptor);
foreach (var filter in filters)
{
ApplicationContext.ConfigureObject(filter.Instance, filter.Instance.GetType().Name);
yield return filter;
}
}
}
public class MvcApplication : SpringMvcApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
<spring>
<context type="Spring.Context.Support.WebApplicationContext, Spring.Web">
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net">
<object id="HomeController" type="SpringActionFilterSample.Controllers.HomeController, SpringActionFilterSample" singleton="false">
<property name="Message" value=":-) Test message from spring.net."/>
</object>
<object id="FilterProvider" type="SpringActionFilterSample.FilterProvider, SpringActionFilterSample">
</object>
<object id="SpringActionFilterAttribute" type="SpringActionFilterSample.SpringActionFilterAttribute, SpringActionFilterSample" singleton="false">
<property name="Message" value="Test message from spring.net."/>
</object>
</objects>
</spring>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment