ASP.NET MVC3 MEFContrib.Mvc3全局动作过滤器

时间:2011-10-26 18:45:17

标签: asp.net asp.net-mvc-3 mef

我正在将ME的MEFContrib.MVC3用于我的MVC3应用程序。这样可以很好地注入我的控制器。

我现在需要创建一个也使用DI的自定义全局动作过滤器。我能够成功注入我的自定义FilterProvider,但不知道如何注入动作过滤器本身。

过滤提供商

[Export(typeof(IFilterProvider))]
public class MefFilterAttributeProvider
    : FilterAttributeFilterProvider
{
    [Import]
    IAccountService _AccountService;

    [ImportingConstructor]
    public MefFilterAttributeProvider(IAccountService accountService)
    {
        //MefContrib.Mvc3 successfully detects and injects
        this._AccountService = accountService;
    }

    public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        List<Filter> filters = new List<Filter>();
        filters.AddRange(base.GetFilters(controllerContext, actionDescriptor));
        filters.AddRange(((IFilterProvider)GlobalFilters.Filters).GetFilters(controllerContext, actionDescriptor));

        foreach (var filter in filters)
        {
            //Custom filter is detected in the list of filters
            //Do I need to add something here to pass the injection to the custom filter??
            yield return filter;
        }
    }
}

自定义过滤器

public class ClinicalFrameworkSessionSate : ActionFilterAttribute
{
    IAccountService accountService;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //base.OnActionExecuting(filterContext);

        if (filterContext.HttpContext.Session != null)
        {
            //Session has timed out
            if (filterContext.HttpContext.Session["UserSites"] == null || filterContext.HttpContext.Session["UserDepts"] == null)
            {
                //Recreate the session
                User usr = this.accountService.GetUser(filterContext.HttpContext.User.Identity.Name);
                filterContext.HttpContext.Session["UserSites"] = usr.Sites.ToList();
                filterContext.HttpContext.Session["UserDepts"] = usr.Departments.ToList();
            }
        } 


    }

}

我已经看过如何使用Ninject,AutoFac等进行注入的示例,但似乎无法找到使用MefContrib和MefContrib.Mvc3的示例。

非常感谢任何帮助。

0 个答案:

没有答案