I am trying to use Ninject for IoC with ASP.NET MVC 5.
My controller has a constructor like this:
private readonly IUnitOfWork _unit;
private readonly IContactService contactService;
public ContactsController(IUnitOfWork unit, IContactService contactService)
{
this._unit = unit;
this._contactService = contactService;
}
So the ContactService
has a constructor (IUnitOfWork unit) and should share the same instance of the IUnitOfWork, but Ninject is giving a new different instance. My ContactService derives of a class with this constructor:
public ServiceBase(IUnitOfWork unit)
{
_unit = unit;
_repository = _unit.GetRepository<TEntity>();
}
My ninject config bindings:
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IContactService>().To<ContactService>().InRequestScope();;
}
I hope that InRequestScope()
give the same instance per request, but that is not happening.
InRequestScope()
is not working it's usually due to a misconfiguration of Ninject / not using the right packages. There's quite a few posts on stackoverflow regarding that matter. For example stackoverflow.com/questions/10591203/… and I think there was/is an issue where the order in which you install the packages can break it,... not sure if this is still the case, though. – BatteryBackupUnit