1
votes

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.

1
And how do you know that it's not the same instance? And can you show the constructor of ContactService?Erik Funkenbusch
If 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
You should be right @BatteryBackupUnit. In fact I am reusing a config from another project, wich does'nt uses ninject.web. I will check that. Thanks.iuristona
@ErikFunkenbusch, I now because I my code doesnt works appropriately, so I checked it.iuristona

1 Answers

1
votes

I had exactly the same problem now. I had Ninject and Ninject.Web.Common packages installed and I was injecting dependencies using my custom NinjectControllerFactory. Using Erik's response linked by BatteryBackupUnit's in comments, I have decided to uninstall my Ninject packages and I have installed Ninject.MVC5 package.

The package generated a NinjectWebCommon.cs Ninject confgiuration file in the App_Start folder. The only thing you need to do is to copy your bindings to RegisterServices method in NinjectWebCommon.cs file and stop using your custom NinjectControllerFactory (if you have one).

It solved my problem, hope it solves your problem as well.