2015-02-23 104 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是让您在一个位置设置你的依赖关系,然后在运行时注入在控制器或服务或任何使用这些依赖关系。