2015-02-23 48 views
1

鬆散耦合的適當架構如果有人能夠爲構建ASP.NET MVC Web應用程序的正確架構提供建議,我將不勝感激。適合與Ninject,ASP.NET MVC 5

我貨幣工作MVC 5 Web應用程序,與ADO.NET Entity Data Model它採用現有數據庫。該應用程序主要使用CRUD操作。

我對我試圖使用以實現鬆耦合的設計模式有所懷疑。我還想使用Ninject依賴注入器。

因此,我的解決方案包括3個項目:Abstractions,MVCWebApplicationDAL。 我想獲得關於構建Abstractions項目的建議。

首先,我已經爲我的db實體定義了視圖模型。我不使用適配器模式,相反,我會用AutoMapper映射數據庫和視圖模型類:

namespace MVCWebApplication.Models 
{ 
    public class CustomerVM 
    { 
      public int ID {get; set;} 
      public string Name {get; set;} 
      public Contract Contract {get; set;} 
    } 
    public class ContractVM 
    { 
     public string ContractNo {get; set;} //ID 
     pulic DateTime AgreementDate {get; set;} 
    } 
} 

通用倉庫

namespace Abstractions 
{ 
    public interface IRepository<T> 
    { 
     T Find(object pk); 
     IQueryable<T> GetAll();  
     void Insert(T entity);  
     //... 
    } 
    public class Repository<T> : IRepository<T> where T : class 
    {  
     public DbContext context; 
     public DbSet<T> dbset; 
     public Repository(DbContext context) 
     { 
      this.context = context; 
      dbset = context.Set<T>(); 
     } 

     //implementation   
    } 
} 

而且的UnitOfWork這使我對倉庫的訪問:

namespace Abstractions 
{ 
    public interface IUnitOfWork : IDisposable 
    { 
     IRepository<Customer> CustomerRepository { get; } //Customer is DB entity 
     IRepository<Contract> ContractRepository { get; } //Contractis DB entity 
     //other repositories 
     void Save();   
    } 


    public partial class UnitOfWork : IUnitOfWork 
    { 
     private IRepository<Customer> _customerRepository; 
     private IRepository<Contract> _contractRepository; 
     private CREntities _context; 
     public UnitOfWork() 
     { 
      _context = new CREntities(); 
     } 
     public IRepository<Customer> CustomerRepository 
     {     
      get 
      { 
       if (_customerRepository == null) 
        _customerRepository = new Repository<Customer>(_context); 
       return _customerRepository; 
      } 
     } 
     //other repositories, save & dispose .. 

    } 
} 

App_Start我有:

private static void RegisterServices(IKernel kernel) 
{ 
    kernel.Bind<IUnitOfWork>().To<UnitOfWork>();     
    kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)); 
} 

那麼,我的問題是這種方法合宜嗎? Ninject在這裏有什麼感覺?

非常感謝

+0

如果您正在構建一個CRUD應用程序,那麼我可能會直接將DbContext注入到控制器中。爲什麼要使用所有的抽象?或者爲什麼要使用MVC?只需使用LightSwitch構建應用程序即可。 – Steven 2015-02-23 07:33:23

+0

我想使用更高級的工具,並嘗試構建未來項目擴展的架構。 – 2015-02-23 07:35:44

回答

0

我對你的方法,其漂亮和有大約在大的應用程序使用它很多人視圖。所以不要擔心。

一個建議,在你的上面的代碼中,你可以直接使用IRepository而不是使用UnitOfWork.XXXRepository。你有通用的倉庫,它可以與任何實體(客戶,合同或新實體)一起工作

有了UnitOfWork類的問題是,當你需要另一個倉庫(對於一個新實體)時,你需要改變UnitOfWork類(打破關閉原則)。

Ninject在這裏有什麼意義?

我不知道如果我理解你的問題充分,Ninject是讓您在一個位置設置你的依賴關係,然後在運行時注入在控制器或服務或任何使用這些依賴關係。