C# ASP.NET MVC应用程序的适当分层和依赖项注入
我有一个项目,有三层 第一个是DAL 第二是域名 第三是介绍 我在我的域层(ICategoryRepository)中创建了一个接口,下面是代码C# ASP.NET MVC应用程序的适当分层和依赖项注入,c#,asp.net-mvc,c#-4.0,inversion-of-control,C#,Asp.net Mvc,C# 4.0,Inversion Of Control,我有一个项目,有三层 第一个是DAL 第二是域名 第三是介绍 我在我的域层(ICategoryRepository)中创建了一个接口,下面是代码 public interface ICategoryRepository { List<CategoryDTO> GetCategory(); } 公共接口ICategoryRepository { List GetCategory(); } 我在DAL中创建了一个类来实现域中的ICategoryRepository publi
public interface ICategoryRepository
{
List<CategoryDTO> GetCategory();
}
公共接口ICategoryRepository
{
List GetCategory();
}
我在DAL中创建了一个类来实现域中的ICategoryRepository
public class CategoryRepository : ICategoryRepository
{
BookInfoContext _context;
public List<CategoryDTO> GetCategory()
{
_context = new BookInfoContext();
var categoryDto = _context.Categories
.Select(c => new CategoryDTO
{
CategoryId = c.CategroyId,
CategoryName = c.CategoryName
}).ToList();
return categoryDto;
}
}
public类CategoryRepository:ICategoryRepository
{
BookInfoContext(语境);;
公共列表GetCategory()
{
_context=newbookinfocontext();
var categoryDto=\u context.Categories
.选择(c=>new CategoryTo
{
CategoryId=c.CategroyId,
CategoryName=c.CategoryName
}).ToList();
返回类别到;
}
}
然后,我在我的域中创建一个类,并将ICategoryRepository作为参数传递到构造函数中
public class CategoryService
{
ICategoryRepository _categoryService;
public CategoryService(ICategoryRepository categoryService)
{
this._categoryService = categoryService;
}
public List<CategoryDTO> GetCategory()
{
return _categoryService.GetCategory();
}
}
公共类类别服务
{
ICategoryRepository_分类服务;
公共类别服务(ICategoryRepository类别服务)
{
本._categoryService=categoryService;
}
公共列表GetCategory()
{
return _categoryService.GetCategory();
}
}
我这样做是为了反转控件。取而代之的是我的域将依赖于DAL,我反转控件,使myDAL依赖于我的域
我的问题是,每次调用表示层中的CategoryService时,我都需要将ICategoryRepository作为DAL中构造函数的参数传递。我不希望我的表示层依赖于我的DAL
有什么建议吗
谢谢,您可以使用依赖项注入。在asp.net mvc中,我们有一个
IDepencyResolver
接口,该接口注入对控制器依赖项及其依赖项的依赖项。要做到这一点,您需要一个容器来轻松地注入您的dpendencies,例如sample、MS Unity、Ninject等。。并在容器上注册所有类型,以使其知道如何解决依赖关系
设置了容器
和依赖解析程序
后,您可以在控制器
上拥有服务
的依赖关系,例如:
public class CategoryController
{
private readonly ICategoryService _categoryService;
// inject by constructor..
public CategoryController(ICategoryService categoryService)
{
_categoryService = categoryService;
}
public ActionResult Index()
{
var categories = _categoryService.GetCategory();
return View(categories);
}
}
在这种情况下,容器将看到控制器需要该服务,而该服务需要一个存储库。它将为您解决所有问题,因为您已经注册了这些类型
看看这篇文章:
我是否需要更改类别服务中的任何内容。。?我尝试该代码,它将返回空值。我使用ninject来解决依赖关系,但当我尝试绑定时,会出现错误。。我正在使用这个代码内核进行绑定。Bind().To();我不知道ninject,但作为任何容器,您必须注册所有依赖项:存储库和服务,以便容器知道如何解析树上的所有依赖项:
controller
->service
->存储库
。你注册了你的存储库吗?你是对的,我只需要注册我的存储库。。kernel.Bind().To()。我现在的问题是我的表示层依赖于我的DAL。。感谢bro的帮助Nice,但这只是一个提示,它不会对您的视图产生任何依赖,只是ViewModels