Question

I've an ASP.NET MVC application using Ninject3 (NuGet install). The solution contains:

  • an MVC project (composition root);
  • a Domain Model project;
  • a Data Layer project;
  • a scheduler project (running scheduled jobs within a windows service and holding an alternative composition root);
  • some other projects.

I'm following the approach to have many small modules spread across the projects defining the bindings. The two composition roots use exactly the same bindings.

I cannot figure out how to configure scope for the modules within the class libraries. For example, given these bindings:

Bind<IDomainService1>()
  .To<Service1Impl>()
  .InSingletonScope(); //This should always be a singleton

Bind<IDomainService2>()
  .To<Service2Impl>(); //No scope specified

I would always want a single instance of Service1Impl, whereas scope for Service2Impl should depend on the composition root used. MVC project should have InRequestScope() for Service2Impl (and for all other bindings with unspecified scope). Scheduler project, which does not run within an http context, should use InThreadScope().

Is this approach correct? If yes, what is the right way of configuring this behaviour?

Was it helpful?

Solution

In Ninject, not specifying the scope means InTransientScope().

Your choices are to either duplicate the bindings or create a custom InScope() scoping rule for the binding.

The cleanest solution (especially given that MVC is already in play) is for you to create a plugin that slots into the InRequestScope() mechanism.

There is a CreateScope() method which currently has minimal documentation in the ninject.extensions.namedscope README, which is used like this. It requires you to select 'Include Prerelease' in NuGet. (And I should be writing a wiki article on it but I have too many other things on my plate...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top