在 mvc 5 ef 6 中将 ninject 与存储库一起使用

Using ninject with repositories, in mvc 5 ef 6

我用 ninject 建立了我的第一个 mvc 项目,我不确定我是否完全理解这一点。我有以下简单的设置。 我使用 entity framework 6 作为我的 orm。

客户资料库

 public class CustomerRepository : ICustomerRepository
 {
    private readonly ApplicationDbContext db;

    public CustomerRepository(ApplicationDbContext db)
    {
        this.db = db;
    }

    public IEnumerable<Customer> GetAll()
    {
        return this.db.Customers.ToList();
    }

}

ICustomerRepository

  public interface ICustomerRepository
  {
    IEnumerable<Customer> GetAll();
  }

Ninject

   private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<ICustomerRepository>().To<CustomerRepository>().InRequestScope();
        kernel.Bind<ICustomerDetailsRepository>().To<CustomerDetailsRepository>().InRequestScope();

        kernel.Bind<ApplicationDbContext>().To<ApplicationDbContext>().InRequestScope();
    }

控制器

 public HomeController(ICustomerRepository customerRepository, ICustomerDetailsRepository customerDetailsRepository)
    {
        this.customerRepository = customerRepository;
        this.customerDetailsRepository = customerDetailsRepository;

    }

如您所见,我从同一个控制器调用两个存储库。两个存储库的设置方式完全相同。 我的两个存储库在请求时是否会使用相同的 dbcontext,之后会自动处理吗??

这不是现实生活中的设置。我让尝试理解 ninject 的工作原理变得非常基础。

您将绑定配置为 InRequestScope 的事实意味着请求的对象将在新请求开始后第一次解析时创建,并且对于同一对象内的每个后续解析请求,您将获得相同的实例。

请记住,请求的生命周期由 HttpContext.Current 对象的生命周期决定。

仅供参考:

如你所见here:

  • InThreadScope 将对象的生命周期与 System.Threading.Thread.CurrentThread
  • 的生命周期相匹配
  • InSingletonScope 将对象的生命周期与 Ninject 的 Kernel
  • 的生命周期相匹配
  • InTransientScope 将对象的生命周期与 null
  • 的生命周期相匹配

更新

关于您对实施 Dispose() 的人的评论: 即使您不手动处理对象,当依赖注入容器处理您的对象时,如果它实现了 IDisposable

,它也会调用 dispose 方法