I'm trying to send a command from a filter in my MVC4 project to my command processor.
The problem:
I can't get an NServiceBus instance in the filter to fill.
The components:
- ASP.NET MVC 4
- NServiceBus version 3
- StructureMap
The Attribute/Filter:
namespace AMS.WebApp.Filters
{
public class AMSAuthorizeAttribute : AuthorizeAttribute
{
public IBus Bus { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool accessGranted = false;
accessGranted = base.AuthorizeCore(httpContext);
// arbitrary command, don't worry about it
// Why is Bus still null?
var requestAccess = new RequestingAccess();
Bus.Send("AMS.AccessControl.CommandProcessor", requestAccess);
//if(isAdmin)
// accessGranted = true;
#if DEBUG
accessGranted = true;
#endif
return accessGranted;
}
}
}
The IOC Code:
using AMS.WebApp.Filters;
using NServiceBus;
using StructureMap;
namespace AMS.WebApp.DependencyResolution {
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory();
scan.WithDefaultConventions();
});
//This doesn't work
//x.SetAllProperties(y => y.OfType<IBus>());
//Neither does this
//x.ForConcreteType<AMSAuthorizeAttribute>()
// .Configure
// .Setter<IBus>(a => a.Bus)
// .IsTheDefault();
});
return ObjectFactory.Container;
}
}
}
Also, my attempt to bypass structuremap completely by passing in the bus instance from the controller resulted in:
An object reference is required for the non-static field, method, or property
At this point I'm pretty sure its something awkward with attributes/filters and structuremap, but I'm not really sure what that is.
WARNING: the accepted answer does not fix the actual problem of getting nservicebus in an action filter, but it does address how to get DI in an action filter. See ASP.NET MVC4 NServiceBus Attribute/Filter StructureMap for the Nservicebus specific question