我編輯我的整個問題注入依賴,所以不知道:)Bestpractice DI與ASP.NET MVC和StructureMap - 如何在一個ActionResult
嗯,我想有一個ActionResult
這需要域模型數據和一些額外的參數,即用於分頁列表的頁面索引和頁面大小。它根據Web請求的種類(不管是否是ajax請求)返回PartialViewResult或ViewResult來決定它自己。
通過使用IMappingService自動映射所緩存的數據,IMappingService負責將任何域模型數據轉換爲視圖模型。 爲簡單起見,MappingService使用AutoMapper。
MappingActionResult:
public abstract class MappingActionResult : ActionResult
{
public static IMappingService MappingService;
}
BaseHybridViewResult:
public abstract class BaseHybridViewResult : MappingActionResult
{
public const string defaultViewName = "Grid";
public string ViewNameForAjaxRequest { get; set; }
public object ViewModel { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null) throw new ArgumentNullException("context");
var usePartial = ShouldUsePartial(context);
ActionResult res = GetInnerViewResult(usePartial);
res.ExecuteResult(context);
}
private ActionResult GetInnerViewResult(bool usePartial)
{
ViewDataDictionary viewDataDictionary = new ViewDataDictionary(ViewModel);
if (String.IsNullOrEmpty(ViewNameForAjaxRequest))
{
ViewNameForAjaxRequest = defaultViewName;
}
if (usePartial)
{
return new PartialViewResult { ViewData = viewDataDictionary, ViewName = ViewNameForAjaxRequest };
}
return new ViewResult { ViewData = viewDataDictionary };
}
private static bool ShouldUsePartial(ControllerContext context)
{
return context.HttpContext.Request.IsAjaxRequest();
}
}
AutoMappedHybridViewResult:
public ActionResult Index(int page = 1)
{
return new AutoMappedHybridViewResult<TeamEmployee, TeamEmployeeForm>(_teamEmployeeRepository.GetPagedEmployees(page, PageSize));
}
:在控制器
public class AutoMappedHybridViewResult<TSourceElement, TDestinationElement> : BaseHybridViewResult
{
public AutoMappedHybridViewResult(PagedList<TSourceElement> pagedList)
{
ViewModel = MappingService.MapToViewModelPagedList<TSourceElement, TDestinationElement>(pagedList);
}
public AutoMappedHybridViewResult(PagedList<TSourceElement> pagedList, string viewNameForAjaxRequest)
{
ViewNameForAjaxRequest = viewNameForAjaxRequest;
ViewModel = MappingService.MapToViewModelPagedList<TSourceElement, TDestinationElement>(pagedList);
}
public AutoMappedHybridViewResult(TSourceElement model)
{
ViewModel = MappingService.Map<TSourceElement, TDestinationElement>(model);
}
public AutoMappedHybridViewResult(TSourceElement model, string viewNameForAjaxRequest)
{
ViewNameForAjaxRequest = viewNameForAjaxRequest;
ViewModel = MappingService.Map<TSourceElement, TDestinationElement>(model);
}
}
用法
因此,您可以看到隱藏了IMappingService
。當使用AutoMappedHybridViewResult
時,控制器不應該知道有關IMappingService
接口的任何信息。
是MappingActionResult
與static IMappingServer
適當還是我違反DI原則?
我已經更新了我的問題 – Rookian 2010-10-02 19:51:32
那麼你的工廠返回? PagedList或(Partial-)ViewResult? –
Rookian
2010-10-06 20:11:20
我更新了我的答案,它會返回查看結果 – 2010-10-06 22:38:50