【发布时间】:2017-06-20 09:49:41
【问题描述】:
我正在使用 ASP.NET MVC 和洋葱架构制作网站。我有以下架构:
- 域:实体/域接口
- 存储库:使用实体框架代码优先方法的通用存储库(目前)
- 服务:调用存储库的通用服务
- MVC
现在我试图在我的控制器中创建一个方法来开始测试我在Repository 和Service 中实现的方法,但我很难知道我可以在这个控制器中创建什么。我想在Repository 中测试一个简单的Get 方法,但要做到这一点,我需要在我的控制器中使用GenericService 对象和GenericRepository 对象。为了演示我的意思,这里是我的 GenericRepository 的 sn-p(我将跳过接口):
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 的 dbcontext):
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();
}
}
这是允许的吗?根据 Jeffrey Palermo 的说法,UI 可以依赖于 Service 和 Domain,所以我不知道 Repository。从技术上讲,我没有使用来自 repository 的方法,但我确实需要添加对项目的引用。
如果我不能,那么如果我没有GenericRepository,我该如何创建一个新的GenericService?有没有更好的方法来实例化我的对象?
编辑我认为我的问题的答案存在于Startup.cs 中,我可以在其中输入service.addScoped(typeof(IGenericRepository<>),typeof(GenericRepository<>)); 之类的内容
但我不确定这一点,有什么想法吗?
【问题讨论】:
标签: asp.net-mvc onion-architecture