如何使用StructureMap将属性注入自定义ActionFilterAttribute?

时间:2013-09-17 08:42:34

标签: c# asp.net-mvc-4 structuremap custom-action-filter

注射在我的解决方案中正常工作,除了海关ActionFilterAttribute 下面是一个示例:我想使用注入将属性UserModel填充到以下ActionFilterAttribute中。

public class UserFilterAttribute : ActionFilterAttribute
{
    public IUserModel UserModel { get; set; }

    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        // here is my problem : this.UserModel is always null

        base.OnActionExecuting(actionContext);
    }
}

Global.asax.cs:

private void ConfigureDependencies()
{
    Guid userId = new Guid();

    // Register models
    IContainer container = new Container(cfg =>
    {
        cfg.Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
        });

        cfg.For<IFilterProvider>().Use<StructureMapFilterProvider>();
        cfg.For<IUserModel>().Use<UserModel>().Ctor<Guid>().Is(userId);
        cfg.SetAllProperties(x => { x.OfType<IUserModel>(); });

    });

    ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory(container));
    DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
}

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
    this.ConfigureDependencies();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}

FilterConfig.cs:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new UserFilterAttribute());
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将IController添加到扫描程序

cfg.Scan(scan =>
{
    scan.TheCallingAssembly();
    scan.WithDefaultConventions();
    scan.AddAllTypesOf<IController>();
});