At the moment, I have a custom ControllerFactory into which I inject my Unity container:
in global.asax Application_Start():
var container = InitCont
I would do this slightly differently. I would:
install the unity.mvc3 nuget package
call the bootstrapped.initialise() as mentioned in the txt doc the package adds to the project
define your IMetadataService mapping in the initialize to your Concrete type
add IMetadataService to your constructor
The difference between your implementation and the article you references is you use Func, which Im not sure if that adds a different problem to the mix here. I have to imagine it does as the above method (without Func) works fine for me.
Edit: Brad Wilson's code worked just fine for me here: http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html
Applicable parts (please see the link above)
Global.asax.cs
protected void Application_Start() {
// ...
var oldProvider = FilterProviders.Providers.Single(
f => f is FilterAttributeFilterProvider
);
FilterProviders.Providers.Remove(oldProvider);
var container = new UnityContainer();
var provider = new UnityFilterAttributeFilterProvider(container);
FilterProviders.Providers.Add(provider);
// ...
}
The filter itself:
using System;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
public class InjectedFilterAttribute : ActionFilterAttribute {
[Dependency]
public IMathService MathService { get; set; }
public override void OnResultExecuted(ResultExecutedContext filterContext) {
filterContext.HttpContext.Response.Write(
String.Format("The filter says 2 + 3 is {0}.
",
MathService.Add(2, 3))
);
}
}
and UnityFilterAttributeFilterProvider.cs
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider {
private IUnityContainer _container;
public UnityFilterAttributeFilterProvider(IUnityContainer container) {
_container = container;
}
protected override IEnumerable GetControllerAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
var attributes = base.GetControllerAttributes(controllerContext,
actionDescriptor);
foreach (var attribute in attributes) {
_container.BuildUp(attribute.GetType(), attribute);
}
return attributes;
}
protected override IEnumerable GetActionAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
var attributes = base.GetActionAttributes(controllerContext,
actionDescriptor);
foreach (var attribute in attributes) {
_container.BuildUp(attribute.GetType(), attribute);
}
return attributes;
}
}