c# - 我可以重构模型 View 查询处理程序吗?

标签 c# asp.net-mvc asp.net-mvc-4 architecture cqrs

在我们的 MVC 应用程序中,我们所有的读取操作作为参数采用查询实现:

public interface IQuery<out TResponse> { }

在操作中,查询被传递到定位处理程序并返回 View 模型的总线。所以 Controller 现在看起来像这样:

   public ActionResult Edit(DetailsQuery query)
    {
        var model = mediator.Request(query);
        return View(model);
    }

实际上只是将查询传递给我们的调解器并返回结果。我们有数百个看起来像这样的 Action 。有一个奇怪的 Action 会做一些有条件的事情(我会保留原样)但其余的只是一次又一次地相同的样板。我们有一百多个不同的查询

如何将其重构为更明确的内容?我想转移到模型 View 查询处理程序而不是样板 Controller 操作,它只是将查询传递给总线并将模型返回给 View 。

我应该在 MVC 中查看哪些扩展点?实际上,不必编写操作处理程序 - 只需使用一些自动方法将强类型查询连接在一起并返回正确的 ViewModel。

如果可以?我是不是该?我只是不喜欢看到数百个看起来都一样的 Action 。

最佳答案

首先,感谢帖子的链接 "Put your controllers on a diet: GETs and queries" .我的代码示例使用了它的类型。

我的解决方案还涉及使用 Action 过滤器作为注入(inject)通用行为的点。

Controller 非常简单,看起来像@Kambiz Shahim 的:

[QueryFilter]
public class ConferenceController : Controller
{
    public ActionResult Index(IndexQuery query)
    {
        return View();
    }

    public ViewResult Show(ShowQuery query)
    {
        return View();
    }

    public ActionResult Edit(EditQuery query)
    {
        return View();
    }
}

正在处理 QueryFilterAttribute我意识到 IMediator并且它的实现可以省略。知道解析 IQueryHandler<,> 实例的查询类型就足够了通过 IoC。

在我的示例中 Castle Windsor和实现 'Service Locator'模式被使用。

public class QueryFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        object query = filterContext.ActionParameters["query"];
        Type queryType = query.GetType();
        Type modelType = queryType.GetInterfaces()[0].GetGenericArguments()[0];

        var handlerType = typeof(IQueryHandler<,>).MakeGenericType(queryType, modelType);

        // Here you should resolve your IQueryHandler<,> using IoC
        // 'Service Locator' pattern is used as quick-and-dirty solution to show that code works.
        var handler = ComponentLocator.GetComponent(handlerType) as IQueryHandler;

        var model = handler.Handle(query);
        filterContext.Controller.ViewData.Model = model;
    }
}

IQueryHandler添加接口(interface)以避免使用反射

/// <summary>
/// All derived handlers can be refactored using generics. But in the real world handling logic can be completely different.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
public interface IQueryHandler<in TQuery, out TResponse> : IQueryHandler
    where TQuery : IQuery<TResponse>
{
    TResponse Handle(TQuery query);
}

/// <summary>
/// This interface is used in order to invoke 'Handle' for any query type.
/// </summary>
public interface IQueryHandler
{
    object Handle(object query);
}

/// <summary>
/// Implements 'Handle' of 'IQueryHandler' interface explicitly to restrict its invocation.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
public abstract class QueryHandlerBase<TQuery, TResponse> : IQueryHandler<TQuery, TResponse>
    where TQuery : IQuery<TResponse>
{
    public abstract TResponse Handle(TQuery query);

    object IQueryHandler.Handle(object query)
    {
        return Handle((TQuery)query);
    }
}

类型应该被注册 in Global.asax.cs

        container.Register(Component.For<ISession>().ImplementedBy<FakeSession>());
        container.Register(
            Classes.FromThisAssembly()
                .BasedOn(typeof(IQueryHandler<,>))
                .WithService.Base()
                .LifestylePerWebRequest());

有一个link to gist on github包含所有代码。

关于c# - 我可以重构模型 View 查询处理程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19833120/

相关文章:

c# - 使用 DisplayFormat 时未在 View 中设置日期格式

c# - 使用 iTextSharp 打开另存为窗口

c# - 以编程方式获取 Windows 用户帐户的数量

c# - 使用 LINQ 在 C# 中查找数字数组的累加和

c# - 创建 Linq XML 文档时为 "Non white space characters cannot be added to content"

asp.net-mvc - N次登录失败后如何显示验证码?

c# - 单独项目中 MVC 解决方案中的 Web API

c# - 缺少根元素。异常(exception)

c# - 如何从 Web 应用程序调用 Windows 服务方法

mysql - INSERT 语句与 FOREIGN KEY 约束冲突2