【问题标题】:How to inject a property into a custom ActionFilterAttribute using StructureMap?如何使用 StructureMap 将属性注入自定义 ActionFilterAttribute?
【发布时间】:2013-09-17 08:42:34
【问题描述】:

注入在我的解决方案中正常工作,但海关 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());
    }
}

【问题讨论】:

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


【解决方案1】:

尝试将IController 添加到您的扫描仪

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

【讨论】:

  • 我的控制器中的注入已经起作用。但是,我“以防万一”测试了您的建议,但没有任何改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多