ASP.NET MVC正确分层应用程序和依赖注入

时间:2013-07-19 11:21:57

标签: c# asp.net-mvc c#-4.0 inversion-of-control

我有一个有三层的项目。

第一是DAL

第二是域

第三是演示文稿

我在我的域层(ICategoryRepository)中创建了一个接口,这里是代码

public interface ICategoryRepository
{
    List<CategoryDTO> 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;
    }
}

然后我在我的Domain中创建一个类,并在我的构造函数中将ICategoryRepository作为参数传递。

public class CategoryService
{

    ICategoryRepository _categoryService;

    public CategoryService(ICategoryRepository categoryService)
    {
        this._categoryService = categoryService;
    }

    public List<CategoryDTO> GetCategory()
    {
        return _categoryService.GetCategory();
    }
}

我这样做是为了反转控件。而不是我的域将取决于DAL我反转控件,以便myDAL将取决于我的DOMAIN。

我的问题是,每次我在Presentation Layer中调用CategoryService时,我都需要传递ICategoryRepository作为DAL中构造函数的参数。我不希望我的表示层依赖于我的DAL。

有什么建议吗?

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以使用依赖注入。在asp.net mvc中,我们有一个IDepencyResolver接口,它注入依赖于控制器依赖关系及其依赖关系。要做到这一点,你需要一个易于注入你的dpendencies的容器,例如样本,MS Unity,Ninject等。并在容器上注册所有类型,知道如何解决你的依赖。

设置ContainerDependencyResolver后,您的service可能会依赖controller作为示例:

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);
   }

}

在这种情况下,Container将看到控制器需要服务,并且此服务需要存储库。它将为您解决所有问题,因为您已经注册了这些类型。

看看这篇文章: http://xhalent.wordpress.com/2011/01/17/using-unity-as-a-dependency-resolver-asp-net-mvc-3/

相关问题