gpt4 book ai didi

asp.net-mvc - 如何使用Unity和asp.net mvc在 Action 过滤器上执行属性注入(inject)?

转载 作者:行者123 更新时间:2023-12-02 02:10:29 27 4
gpt4 key购买 nike

我正在尝试通过属性注入(inject)让依赖注入(inject)在我的 Action 过滤器上工作。我不知道如何自动设置过滤器的依赖关系。这是我到目前为止的代码。

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();
}
}

最佳答案

答案是:

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);
}
}

关于asp.net-mvc - 如何使用Unity和asp.net mvc在 Action 过滤器上执行属性注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/738828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com