Ninject Web Application: should all bindings be InRequestScope ()?

I have a web application made in asp.net mvc and I use Ninject to bind interfaces.

At the moment I have this:

// Db Context kernel.Bind<DbContext>().To<DbEntities>().InRequestScope(); // Repositories - which are using instance of DbEntities kernel.Bind<ICustomerRepository>().To<CustomerRepository>(); kernel.Bind<IProductRepository>().To<ProductRepository>(); // Services - which are using instances of Repositories kernel.Bind<ICustomerService>().To<CustomerService>(); kernel.Bind<IProductService>().To<ProductService>(); 

I am linking a DbContext with DbEntities in RequestScope because I want to use the same DbContext in the same web request. After that, he should dispose of it.

But how should the other bindings be? How are they by default?

For example, an IProductRepository that has an instance of DbContext (which one per request) should also have InRequestScope() ?

IProductService has an instance of IProductRepository

How should the bindings be suitable for a web application? (and I do not overload the server memory)

+4
source share
2 answers

For an MVC application, your configuration is fine. It won't make much difference if you bind your repositories in the default transient area or in the request area. As @Mark stated that in the transient area, your dependencies will be introduced as new instances of restricted objects, but in the transaction area they will be created once per request. I prefer a bit more scope for the request and recommend it if you want to do (for example) some caching for each request in your repository.

+3
source

You can leave the repositories as they are. The default scope is such that whenever an IProductRepository is required, a new instance is created.

+1
source

Source: https://habr.com/ru/post/1446161/


All Articles