2013-07-19 45 views
0

我有一个项目,有三层。ASP.NET MVC适当的应用程序和依赖注入分层

一日是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; 
    } 
} 

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

public class CategoryService 
{ 

    ICategoryRepository _categoryService; 

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

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

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

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

有什么建议吗?

谢谢,

回答

1

您可以使用依赖注入。在asp.net mvc中,我们有一个IDepencyResolver接口,用于注入控制器依赖关系及其依赖关系的依赖关系。要做到这一点,你需要一个容器来容易地注入你的附属物,例如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); 
    } 

} 

在这种情况下,容器会看到控制器需要的服务,这种服务需要一个存储库。它会为您解决所有问题,因为您已经注册了这些类型。

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

+0

我需要在我的categoryService改变什么..?我尝试该代码,它将返回空值。我使用ninject来解决依赖关系,但当我尝试绑定时,我得到错误..我绑定使用此代码** kernel.Bind ()。(); ** – RAM

+0

我不知道ninject,但作为任何容器,您必须注册所有依赖项:存储库和服务,以便Container知道如何解析树上的所有依赖关系:'controller' - >'service' - >'repository'。你注册了你的仓库吗? –

+0

你是对的我只需要注册我的仓库.. kernel.Bind ()。到();
。我现在的问题是我的表示层对我的DAL有依赖性。感谢兄弟的帮助 – RAM