我还有另一个 ASP.NET MVC 体系结构问题,我正在慢慢到达那里并将位拼凑在一起,但仍有一些缺失的链接我正在尝试解决。我目前的项目结构如下,我对此很满意(尽管任何建设性的意见都会很棒),我还没有使用 IoC/DI,但会在某个时候,现在只是更大的鱼要炒!!。
我的问题是我在 AppName.Core.Services 命名空间中有域级业务逻辑,这很棒,但我有一些逻辑需要与 HttpContext 交互,后者检查应用程序缓存等中的内容。一个非常简单的示例是一些代码,例如这个:
public int? GetCurrentClientId()
{
int clientId = null;
if (HttpContext.Current.Application["ClientId"] != null)
{
// Use value from application cache if one exists
clientId = (int)HttpContext.Current.Application["ClientId"];
}
else
{
// Lookup using host name of site we are browsing
string hostName = HttpContext.Current.Request.UserHostName.ToLower();
UnitOfWork _unitOfWork = new UnitOfWork();
Client client = _unitOfWork.ClientRepository.GetSingle(x => x.HostName.ToLower() == hostName || x.LocalHostNames.ToLower().Contains(hostName));
if (client != null) clientId = client.Id;
}
return clientId;
}
现在我不能将所有这些都粘贴在 AppName.Core.Services 中,因为它可以感知 HttpContext,所以我将其分解为以下代码,这些代码可以位于 AppName.Core.Services 中,但我不确定在哪里如果需要,我的逻辑会与 HttpContext 等交互以调用它。我不希望它在我的控制器中,但我现在想知道它的最佳位置,什么命名空间和约定等。
public int? GetClientIdFromHostName(string hostName)
{
UnitOfWork _unitOfWork = new UnitOfWork();
Client client = _unitOfWork.ClientRepository.GetSingle(x => x.HostName.ToLower() == hostName || x.LocalHostNames.ToLower().Contains(hostName));
if (client != null) return client.Id;
else return null;
}
我之前对这个主题的研究,以及我在这里问过的一个问题,指向我从控制器访问我的所有服务......但是如果我的服务中不能有基于 HttpContext 的逻辑,它可以去哪里?
ASP.NET MVC - 服务层,每个控制器动作中的单个或多个服务?
项目结构:
AppName.Core (for all my domain objects, DAL, domain services etc... independant and not aware of web specifics HttpContext etc)
> Data
> Data > DataContext.cs
> Data > UnitOfWork.cs
> Entities
> Entities > User.cs
> Entities > Client.cs etc etc
> Migrations
> Migrations > (all the EF code first migrations bits)
> Repository
> Repository > UserRepository.cs
> Repository > ClientRepository.cs
> Repository > GenericRepository.cs etc etc
> Services
> Services > ClientService.cs etc etc
AppName.Web (for all my compiled HttpContext aware code, ViewModels etc... references AppName.Core only)
> AutoMapper
> AutoMapper > Configuration.cs
> Controllers
> Controllers > UserController.cs
> Controllers > ClientController.cs etc etc
> Helpers
> Helpers > HtmlHelpers.cs
> ViewModels
> ViewModels > UserViewModel.cs
> ViewModels > ClientViewModel.cs etc etc
AppName (the ASP.NET MVC website project, no compiled code, Images/Css/JavaScripts etc... references AppName.Web only)
> Content
> Content > Images
> Content > Styles
> Scripts
> Views