I have an existing web project that I converted to use Ninject with the bindings set to InRequestScope.
// binding in AppStart
kernel.Bind<IDbContext>().To<DbContext>().InRequestScope();
...
// business layer
public class BusinessService {
public BusinessService(IDbContext context) {
this.Context = context;
}
private IDbContext Context { get; set; }
public void UpdateUser(int userId) {
User user = this.Context.Users.Single(u => u.UserId == userId);
user.LastUpdated = DateTime.Now;
this.Context.SaveChanges();
}
}
Now, I'm trying to convert a few console apps that use the code in the business layer.
// ... Console App ...
foreach(int userId in usersNeedingToBeUpdated) {
// do stuff to each user
BusinessService businessService = kernel.Get<BusinessService>();
businessLayer.UpdateUser(userId);
}
However, I'm having trouble with understanding the scope. I would like each time I do kernel.Get() for Ninject to give me a new IDbContext and dispose of the old IDbContext. I tried doing
kernel.Bind<IDbContext>().To<DbContext>().InParentScope();
And this works until someone requests the IDbContext directly:
kernel.Get<IDbContext>();
Then I get a null pointer exception because there isn't a parent scope. If I used TransientScope instead, then Ninject doesn't dispose of the IDbContext1. How can I get it to where for every kernel.Get<>() I get a new service as well as new dependencies and the old dependencies are disposed?
I have read this post, but I'm still unsure of what to do.
InRequestScope
works and hopefully giving you enough detail for you to figure out what you need. – qujck