Reputation: 53
I set up my first mvc project with ninject, and im not sure if i understand this fully. I have the following simple setup. I am using entity framework 6 as my orm.
Customer repository
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();
}
Controller
public HomeController(ICustomerRepository customerRepository, ICustomerDetailsRepository customerDetailsRepository)
{
this.customerRepository = customerRepository;
this.customerDetailsRepository = customerDetailsRepository;
}
As you can see, i am calling both repositories from the same controller. Both repositories are setup exactly the same way. Will both my repositories use the same dbcontext when requested, and will it automaticly be disposed afterwards??
This is not a real life setup. I made it really basic to try and understand how ninject work.
Upvotes: 0
Views: 355
Reputation: 2085
The fact that you configured your binding to be InRequestScope
means that the requested object will be created the first time it's resolved after a new request starts, and for every subsequent resolutions of the same object within the same request, you will get the same instance.
Keep in mind that the lifetime of the request is determined by the lifetime of the HttpContext.Current
object.
Just for reference:
As you can see here:
InThreadScope
matches the lifetime of your object to the lifetime of System.Threading.Thread.CurrentThread
InSingletonScope
matches the lifetime of your object to the lifetime of Ninject's Kernel
InTransientScope
matches the lifetime of your object to the lifetime of null
Regarding your comment about people implementing Dispose()
:
Even if you don't dispose your objects manually, when the dependency injection container disposes your object, it calls the dispose
method if it implements IDisposable
Upvotes: 1