ASP.NET MVC4 NServiceBus Attribute/Filter Structur

2019-09-04 14:48发布

I'm having issues getting an instance of IBus in an action filter (attribute).

From Setting IBus Property in MVC Filter, I know that DI and action filters don't play nice, and I got them play nice using the accepted answer. The problem is that getting DI and action filters to play nice breaks NServiceBus.

That same question had a suggestion by John to look at the video store solution to see how to get it done. There are two problems with that answer:

  1. It totally ignores the fact that I'm using StructureMap.
  2. More importantly, using that sample, when I added my own derived authorize filter (see below), the IBus instance is still not being filled.

This is a guess on my part, but I don't think the baked in DI container that NServiceBus has can handle DI into an action filter, either.

//NOTE:
//I added a Filters folder to the project, and stuck this class in there
//This filter will disable authentication when debugging
//Add the attribute to the home controller, and
//If you put a break point at the beginning, IBus doesn't get filled

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

namespace VideoStore.ECommerce.Filters
{
    public class AMSAuthorizeAttribute : AuthorizeAttribute
    {
        public IBus Bus { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool accessGranted = false;

            accessGranted = base.AuthorizeCore(httpContext);

            //if(isAdmin)
            //  accessGranted = true;

#if DEBUG
            accessGranted = true;
#endif

            return accessGranted;
        }
    }
}

When I follow the steps specified in Setting IBus Property in MVC Filter, I get this error StructureMap Exception Code: 202 No Default Instance defined for PluginFamily NServiceBus.Unicast.Subscriptions.ISubscriptionStorage, NServiceBus.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=9fc386479f8a226c

1条回答
▲ chillily
2楼-- · 2019-09-04 15:07

Because filter attributes don't play nice with dependency injection, you may find it's easier just to do this within your filter:

private readonly IBus bus = Configure.Instance.Builder.Build<IBus>();
查看更多
登录 后发表回答