洋葱架构 :尊重应用程序的 MVC 层中的依赖关系



我正在使用 ASP.NET MVC和洋葱架构制作一个网站。我有以下架构:

  1. :实体/域接口
  2. 存储库
  3. :使用实体框架代码优先方法的通用存储库(目前)
  4. 服务
  5. : 调用存储库的通用服务
  6. MVC

现在我正在尝试在我的控制器中创建一种方法,以开始测试我在RepositoryService中实现的方法,并且我很难在这个控制器中创建什么。我想在Repository中测试一个简单的Get方法,但要做到这一点,我需要GenericService对象和GenericRepository我的控制器中的对象。为了说明我的意思,这是我的 GenericRepository 的一个片段(我将跳过接口):

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly PrincipalServerContext context;
private DbSet<T> entities;
public Repository(PrincipalServerContext context)
{
this.context = context;
entities = context.Set<T>();
}
}

现在我的泛型服务:

public class GenericService<T> : IGenericService<T> where T : class
{
private IRepository<T> repository;
public GenericService(IRepository<T> repository)
{
this.repository = repository;
}
public T GetEntity(long id)
{
return repository.Get(id);
}
}

最后,我的问题是,我是否可以在我的控制器中创建这些对象,如下所示(使用我的数据库上下文称为 PrincipalServerContext):

public class NavigationController : Controller
{
private IGenericService<DomainModelClassHere> domainService;
private IGenericRepository<DomainModelClassHere> domainRepo;
private PrincipalServerContext context;
public ActionResult MyMethod(){
context = new PrincipalServerContext();
domainRepo = new GenericRepository<DomainModelClassHere>(context);
domainService = new GenericService<DomainModelClassHere>(domainRepo);
if(domainService.GetEntity(1)==null)
return View("UserNotFound");//Just as an example
return View();
}
}

这是允许的吗?根据杰弗里·巴勒莫的说法,UI可以依赖于ServiceDomain,所以我不知道Repository。从技术上讲,我没有使用repository的方法,但我确实需要添加对项目的引用。

如果我不能,那么如果我没有GenericRepository,我该如何创建新GenericService?有没有更好的方法来实例化我的对象?

编辑我认为我的问题的答案在于Startup.cs我可以在其中放置类似service.addScoped(typeof(IGenericRepository<>),typeof(GenericRepository<>));但我不确定这一点,有什么想法吗?

如果有人遇到同样的问题,我会自己回答这个问题。我们可以在需要时使用配置方法来创建类的实例。在Startup.cs文件中,您必须添加ConfigureServices(IServiceCollection services)方法,并且内部有几个方法可以应用于services来创建这些实例。例如,您可以使用:

services.AddTransient(IGenericRepository, GenericRepository)

服务之间有什么区别。添加瞬态,服务。添加范围和服务。在 Asp.Net 核心 1 中添加单例方法?(此链接解释了方法之间的差异)。

AddTransient在我的情况下很好,因为它在应用程序的整个生命周期内创建了一个对象的实例,这正是我所需要的。这意味着 UI 依赖于解决方案的其余部分,因为 Startup.cs 需要了解Repositories以及Services。 一个很好的答案可以在这里找到:洋葱架构:UI可以依赖于域吗?

最新更新