开发者

Dependency Injection/Property Injection on an asp.NET MVC 2 ActionFilter: Help!

开发者 https://www.devze.com 2023-02-22 22:53 出处:网络
I\'ve been trying to wrap my head around the topics posted at this similar question: Is it possible to use Dependency Injection/IoC on an ASP.NET MVC FilterAttribute?

I've been trying to wrap my head around the topics posted at this similar question:

Is it possible to use Dependency Injection/IoC on an ASP.NET MVC FilterAttribute?

However, I'm just not getting anywhere. Not to mention, all the solutions appear to have dependencies on other libraries which I'm not able to use (MvcContrib, Unity).

Can anyone toss together some code to explain how to make this property injection work? Or if there is another way to make this happen?

Thanks much!

Relevant code 1: Controller

namespace TxRP.Controllers
{
    [GetMasterPageData] 
    public class BaseController : Controller
    {
    }
}

Relevant code 2: ActionFilter

public class GetMasterPageData : ActionFilterAttribute
{
    private IEmployee emp; //<--Need to inject!
    private ICache cache;  //<--Need to inject!

    /// <summary>
    /// ActionFilter attribute w开发者_如何学Pythonhich inserts the user name, access level and any error/warning messages to the MasterPage
    /// Session variables which are consumed primarily by the LogOnUserControl.
    /// The MasterPage will display any warning or error messages.
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
                 //Code
    }


It's not possible to use DI with attributes because they are statically compiled into your classes, so nothing can ever be injected. Some people may tell you that you can use a sort of static factory to get your dependencies, but that's not Dependency Injection - that would be Service Location - which is an anti-pattern.

However, it's possible to combine DI with action filters if you abandon the idea of attributes, but not particularly easy. You'll need to create a custom IActionInvoker, although the easiest way to do that is to derive from ControllerActionInvoker and override its GetFilters method. Here's a blog post that explains how to do that for error handling - you should be able to extrapolate from that.

When you get tired of doing that I'd advice you to switch to composing cross-cutting concerns out of Decorators and other design patterns. In that way you can implement your cross-cutting concerns independently of constraining technology.

0

精彩评论

暂无评论...
验证码 换一张
取 消