Castle Windsor, ASP.NET MVC and Web API in the Same Project

Many thanks to the original source by ArtisanCode on GitHub I’ve enjoyed for solving this problem. You may also enjoy Radenko’s post and Raymund’s post. I hope that you will find what I have learned from these sources helpful. The requirement was running ASP.NET MVC and Web API in the same project with a single inversion of control (IoC) container shared by both, though I never ended up using injection for my MVC controllers as I had planned.

My personal preference in the past has been Castle Windsor, in part because I like the ability to do interception so easily. More on interception in a future post. For now, have a look at how easy it is to wire up. First, we wire up the container in the Application_Start method in your Global.asax.cs class that inherits from System.Web.HttpApplication:

IoC.Instance.Container.Install(new DependencyConfig());
IoC.Instance.Container.BeginScope();	
GlobalConfiguration.Configuration.DependencyResolver = 
   new CastleDependencyResolver(IoC.Instance.Container);

Then we wire up the DependencyConfig class mentioned in the above snippet.

public class DependencyConfig : IWindsorInstaller
{
   public void Install(IWindsorContainer container, IConfigurationStore store)
   {
      //... config stuff ... blah blah blah

      //register a component with a custom interceptor for capturing some aspect
      container.Register(Component.For<IMyComponent>()
         .ImplementedBy<MyComponent>()
         .LifestyleSingleton()
         .Interceptors(InterceptorReference.ForType<MyInterceptor>())
         .Anywhere);

And implement your interceptor with something like this:

public class MyInterceptor : IInterceptor
{
   public void Intercept(IInvocation invocation)
   {
      //do something before the call is executed
      //execute the call
      invocation.Proceed();
	  //do something after the call is executed
   }
}

Now put it all together and you have ApiControllers injecting your components for you. And you can get components directly when you need them using the IoC singleton I wrote like this:

var mycomp = IoC.Instance.Container.Resolve<IMyComponent>();

Here’s the IoC singleton:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Castle.Windsor;

namespace MyCastle
{
   public class IoC
   {
      private static volatile IoC _instance;
      private static object _syncRoot = new object();

      private readonly WindsorContainer container;

      private IoC()
      {
         container = new WindsorContainer();
      }

      public static IoC Instance
      {
         get
         {
            if (null == _instance)
            {
               lock (_syncRoot)
               {
                  if (null == _instance)
                  {
                     _instance = new IoC();
                  }
               }
            }
            return _instance;
         }
      }

      public WindsorContainer Container { get { return container; } }
   }
}

And where does the CastleDependencyResolver and CastleDependencyScope classes come from? That’s the fun part. First, you’ll need two NuGet packages:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Castle.Core" version="3.3.3" targetFramework="net45" />
  <package id="Castle.Windsor" version="3.3.0" targetFramework="net45" />
</packages>

Then you just need the ArtisanCode code for those two classes. For my own use, I’ve modified them a bit in my own projects but you may find that you can use them right out of the box or even adopt the entire WebApiCastleIntegration library.

There you have it.

Context Switching and Task<Result>.ConfigureAwait Method

While heavily involved in a few ASP.NET Web API 2 projects over the past year, I’ve learned from experience that context switching, marshaling between threads when using the async and await constructs in C# can be undesirable.

To avoid the context switching which is undeniably needed in a UI application where you’re offloading work from the UI thread, the default value of “true” for the ConfigureAwait Method on the Task<Result> class, one must set the “continueOnCapturedContext” to false. Like this:

var user = await repo.GetUser(id).ConfigureAwait(false);

There is some debate as to whether this is helpful in an ASP.NET application given the request is handled on a thread pool thread which is returned to the pool while the asynchronous task is running.

The issue I’ve noticed is that in some cases setting the “continueOnCapturedContext” to false, eliminates the need to marshal the continuation of your code back to the original context and use of another thread pool thread. While there are no noticeable performance advantages, I have noticed that I experience fewer threading exceptions when I allow the execution to continue on the thread that just executed my asynchronous work.

Blog Vacation is Over

It's been seven months and two job changes and crazy busy with family, work and life.

Vacation is over.

List of things to blog about.

So much to say, so little time to say it.

ASP.NET MVC 4 Beta Released

I’m excited to watch the rollout of ASP.NET MVC 4 Beta and looking forward to finding the time and a good solid project to take advantage of the new mobile support and Azure SDK.

Here’s a basic list of what’s new.

  • ASP.NET Web API
  • ASP.NET Single Page Application
  • Enhancements to Default Project Templates
  • Mobile Project Template
  • Display Modes
  • jQuery Mobile, the View Switcher, and Browser Overriding
  • Recipes for Code Generation in Visual Studio
  • Task Support for Asynchronous Controllers
  • Azure SDK

I want to hear your ASP.NET MVC 4 stories. Let me know what you think about it. You may get a chance to deep dive before I do, given my current project priorities.

Custom Recursive Model Validation in .NET Using Data Annotations

Need to write your own model validator outside the scope of an application framework such as ASP.NET MVC? A short while ago, I needed to do just that. I was writing a WCF service with a relatively complex data model which required a much greater level of validation than the DataMember attribute’s IsRequired property could provide.

Here’s the solution I found. But first a bit of background.

Validation in ASP.NET MVC 
I’ve been using Data Annotations attributes for view model validation for years in the context of ASP.NET MVC for model validations, client and server side. I always took the server side validation for granted and looked at the client side with greater interest. When getting started with ASP.NET MVC, I used Steve Sanderson’s xVal library. Then I switched to ASP.NET MVC 3’s client side validation.

For client side validation, I’m really starting to like jQuery’s unobtrusive validation and the ASP.NET MVC’s HtmlHelper class and its GetUnobtrusiveValidationAttributes method. And for the server side, view model binding and the ModelState.IsValid property works fine.

Validation Without an App Framework 
But this post is not about client side validation or server side validation in ASP.NET MVC. I had to do the validation against the model in the WCF service which, as far as I know, does not have a nice model validation facility other than its own data model serialization which just throws a nasty exception should the data being passed over the wire not provide required data.

So why not use the same approach used by our friends in the ASP.NET MVC world. A little Google investigation turned up something that looked like exactly what I wanted. I found an answer posted to StackOverflow by Mike Reust which included a link to his DataAnnotationsValidatorRecursive library. (Gotta love StackOverflow.)

After some experimentation, I had made some tweaks to Mike’s code and came up with something that worked the way I wanted it to. Here’s a partial example of a data model and how the ValidateObject with it’s optional MinOccursOnEnumerable can be used to require one or more items to be included in a required complex enumerable type that will get recursively.

[DataMember(IsRequired = true), 
	Required(ErrorMessage = "Employer cannot be null."), 
	ValidateObject]
public Employer Employer { get; set; }


[DataMember(IsRequired = true), 
	Required(ErrorMessage = "Children cannot be null."), 
	ValidateObject(MinOccursOnEnumerable = 1)]
public Child[] Children { get; set; }

Using the recursive validation library is easy. Here’s an example:

//perform validation using DataAnnotations for custom validation messages
List<ValidationResult> results = new List<ValidationResult>();
bool isValid = DataAnnotationsValidator.TryValidateObjectRecursive<MyModelData>(model, results);

//now examine isValid and the results

And here’s the code for the validation extensions and ValidateObject attribute.

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System;

namespace MyValidator
{
	public static class DataAnnotationsValidator
	{
		public static bool TryValidateObject(object obj, ICollection<ValidationResult> results)
		{
			return Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), results, true);
		}

		public static bool TryValidateObjectRecursive<T>(T obj, List<ValidationResult> results)
		{
			bool result = TryValidateObject(obj, results);

			var properties = obj.GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(ValidateObjectAttribute)));

			foreach (var property in properties)
			{
				var valAttrib = property.GetCustomAttributes(typeof(ValidateObjectAttribute), true).FirstOrDefault() as ValidateObjectAttribute;
				var value = obj.GetPropertyValue(property.Name);

				if (value == null || valAttrib == null) continue;

				var asEnumerable = value as IEnumerable;
				if (asEnumerable != null)
				{
					List<object> items = new List<object>();
					foreach (var enumObj in asEnumerable) items.Add(enumObj);
					foreach (var enumObj in items)
					{
						result = TryValidateObjectRecursive(enumObj, results) && result;
					}
					if (items.Count < valAttrib.MinOccursOnEnumerable)
					{
						string errorMessage = valAttrib.ErrorMessage ?? "MinOccursOnEnumerable validation failed.";
						results.Add(new ValidationResult(errorMessage));
						result = false;
					}
				}
				else
				{
					result = TryValidateObjectRecursive(value, results) && result;
				}
			}

			return result;
		}
	}

	public static class ObjectExtensions
	{
		public static object GetPropertyValue(this object o, string propertyName)
		{
			object objValue = string.Empty;

			var propertyInfo = o.GetType().GetProperty(propertyName);
			if (propertyInfo != null)
			{
				objValue = propertyInfo.GetValue(o, null);
			}
			return objValue;
		}
	}
}

You need to use the ValidateObject attribute on any complex type you want validated deeply. I found out the hard way that if you try to validate all reference objects, you get nasty results on DateTime properties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyValidator
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
	public class ValidateObjectAttribute : Attribute
	{
		int _minOccurs = 0;
		//marker for object properties that need to be recursively validated

		public ValidateObjectAttribute() { }

		public int MinOccursOnEnumerable { get { return _minOccurs; } set { _minOccurs = value; } }

		public string ErrorMessage { get; set; }
	}
}

Of course you can take off on this or Mike’s original code and create your own validation library for a WCF service, a business logic layer, or whatever you need. Good luck and please update me on your validation adventures.

ASP.NET MVC Custom Authorize Attribute with Roles Parser

Do you ever get frustrated with the limited nature of the ASP.NET MVC AuthorizeAttribute class’s limited Roles property which provides only a simple comma delimited list and creates a simple OR list? Would you like to be able to exclude specific roles or have a more complex expression such as:

!Guest & ((Admin | Supervisor) | (Lead & Weekend Supervisor))

Well, now you can. All thanks to the random convergence of great minds! (Or perhaps the obsessions of two code monkeys who have no life. You decide.)

While working on a project for a future blog post, I discussed the code with Nick Muhonen of Useable Concepts and MSDN author who offered to write a parser for an authorization strategy in the project that uses attributes similar to the ASP.NET MVC AuthorizeAttribute class.

Nick showed me the parser yesterday and after I agreed to say that I liked the code, he sent it to me with his blessing to use in my blog post project I’ve been working on. As I began to work the code into my project, I realized that this code deserved its own post as a descendant of the real ASP.NET MVC AuthorizeAttribute class for general use in the ASP.NET MVC world. I’m still planning to use the same parser for my future post, but here it is for your general use in your ASP.NET MVC projects.

The power starts in the return value of the RoleParser’s Parse method, the IRule:

public interface IRule
{
  bool Evaluate(Func<string, bool> matcher);
  string ShowRule(int pad);
}

Here’s the simple, but powerful SuperAuthorizeAttribute class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using SuperMvc.RoleRules;

namespace SuperMvc
{
  public class SuperAuthorizeAttribute : AuthorizeAttribute
  {
    private string _superRoles;
    private IRule _superRule;

    public string SuperRoles
    {
      get
      {
        return _superRoles ?? String.Empty;
      }
      set
      {
        _superRoles = value;
        if (!string.IsNullOrWhiteSpace(_superRoles))
        {
          RoleParser parser = new RoleParser();
          _superRule = parser.Parse(_superRoles);
        }
      }
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      base.OnAuthorization(filterContext);
      if (_superRule != null)
      {
        var result = _superRule.Evaluate(role => filterContext.HttpContext.User.IsInRole(role));
        if (!result)
        {
          filterContext.Result = new HttpUnauthorizedResult();
        }
      }
    }
  }
}

You’ll note that the setter on SuperRoles creates a parser instance and generates an IRule for later use in the OnAuthorization override. This allows us to parse once and run many times, making the evaluation even faster.

I’m not going to dive into how the parser works. I’ll let Nick blog about that. The great thing is that it does work and it’s very fast. Here’s how it’s put to use. First a look at the controller code on which we test it and a peek at one or two of the test methods. The HomeController has been modified with some test actions:

//partial listing

public class HomeController : Controller
{
  [SuperAuthorize(SuperRoles = "!Guest")]
  public ActionResult AboutTestOne()
  {
    return RedirectToAction("About");
  }

  [SuperAuthorize(SuperRoles = "Admin & Local Office | Local Office Admin")]
  public ActionResult AboutTestFive()
  {
    return RedirectToAction("About");
  }

  [SuperAuthorize(SuperRoles = "!Guest & !(SuperUser | DaemonUser) & ((Admin & Local Office | Local Office Admin) & !User)")]
  public ActionResult AboutCrazyTwo()
  {
    return RedirectToAction("About");
  }

  public ActionResult About()
  {
    return View();
  }
}

And here’s the tests, including some crucial initialization logic, that allows us to verify the attribute works.

[TestClass]
public class HomeControllerTest
{
  [TestInitialize]
  public void Initialize()
  {
    string[] roles =
      {
         "Admin",
         "User",
         "Local Office"
      };
    HttpContextHelper.SetCurrentContext(new FakePrincipal("Fake", "testuser", true, roles));
  }

  //[SuperAuthorize(SuperRoles = "!Guest")]
  //public ActionResult AboutTestOne()
  [TestMethod]
  public void AboutTestOne()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<RedirectToRouteResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutTestOne");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  //[SuperAuthorize(SuperRoles = "Admin & Local Office | Local Office Admin")]
  //public ActionResult AboutTestFive()
  [TestMethod]
  public void AboutTestFive()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<RedirectToRouteResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutTestFive");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  //[SuperAuthorize(SuperRoles = "!Guest & !(SuperUser | DaemonUser) & ((Admin & Local Office | Local Office Admin) & !User)")]
  //public ActionResult AboutCrazyTwo()
  [TestMethod]
  public void AboutCrazyTwo()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<HttpUnauthorizedResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutCrazyTwo");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  private FakeControllerActionInvoker<TExpectedResult> GetInvoker<TExpectedResult>(out ControllerContext context) where TExpectedResult : ActionResult
  {
    HomeController controller = new HomeController();
    var httpContext = new HttpContextWrapper(HttpContext.Current);
    context = new ControllerContext(httpContext, new RouteData(), controller);
    controller.ControllerContext = context;
    var invoker = new FakeControllerActionInvoker<TExpectedResult>();
    return invoker;
  }
}

All you have to do is download the code and plug in the SuperMvc project into your ASP.NET MVC web project and you too can have the power of parsed roles at your authorization attribute finger tips. Let me know if you like it or find an even better way to accomplish the same things.

SuperMvc.zip (281.93 KB)