4

我正在尝试使用属性注入在我的操作过滤器上进行依赖注入。我不知道如何自动设置过滤器的依赖关系。这是我到目前为止的代码。

public class UnityActionInvoker : ControllerActionInvoker
{
    IUnityContainer container;

    public UnityActionInvoker(IUnityContainer container) {
        this.container = container;
    }

    protected override ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) {
        foreach (var filter in filters) {
            // HELP: dependency injection on all marked filter properties
        }

        return base.InvokeActionMethodWithFilters(controllerContext, filters, actionDescriptor, parameters);
    }
}

public class UnityControllerFactory : DefaultControllerFactory
{
    IUnityContainer container;

    public UnityControllerFactory(IUnityContainer container) {
        this.container = container;
    }

    protected override IController GetControllerInstance(Type controllerType) {
        Controller controller = null;

        if (controllerType != null) {
            if (!typeof(IController).IsAssignableFrom(controllerType)) {
                throw new ArgumentException(string.Format("Type requested is not a controller: {0}", controllerType.Name), "controllerType");
            }

            controller = container.Resolve(controllerType) as Controller;
            controller.ActionInvoker = new UnityActionInvoker(container);
        }

        return controller;
    }
}

public class AccessFilterAttribute : FilterAttribute, IActionFilter
{
    [Dependency]
    public IUserRepository UserRepository { get; set; }

    public void OnActionExecuting(ActionExecutingContext filterContext) {
        throw new NotImplementedException();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext) {
        throw new NotImplementedException();
    }
}
4

1 回答 1

5

答案是:

public class UnityActionInvoker : ControllerActionInvoker
{
    IUnityContainer container;

    public UnityActionInvoker(IUnityContainer container) {
        this.container = container;
    }

    protected override ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) {
        foreach (var filter in filters) {
            container.BuildUp(filter.GetType(), filter);
        }

        return base.InvokeActionMethodWithFilters(controllerContext, filters, actionDescriptor, parameters);
    }
}
于 2009-04-11T00:17:52.390 回答