2

I am very much new to ASP.NET MVC and I need help loading some types in singleton scope using Ninject.

--- existing code looks as ----

List<Type> types = loading some types into list here.

foreach (var type in types.Where(O => O.Name.StartsWith("I")))
{
    Kernel.Bind(type).To(Type.GetType(type.FullName.Replace(".I", ".")));
}

My job is to bind these types in singleton scope and I am not sure how to do that.

Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
mmssaann
  • 1,507
  • 6
  • 27
  • 55

2 Answers2

3

After kernel.Bind().To() put .InSingletonScope()

Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
  • 1
    this line is inside foreach loop.. does it makes any issue like leaving multiple copies ?? – mmssaann Apr 22 '13 at 10:31
  • I'm not sure I understand what you mean by "leaving multiple copies"? The `InSingletonScope()` informs Ninject that for the specified binding, a single instance should be created upon its first resolution and that same instance should be used every time the type is requested. – Trevor Pilley Apr 22 '13 at 10:48
3

Also have a look at the Ninject conventions extension. It makes stuff like this a lot easier. For example you could write it like this instead.

kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.Where(types.Contains)
.BindDefaultInterface()
.Configure(b => b.InSingletonScope()));

Depending on how you get your list of types, this might be written even easier. Just check out the documentation and the samples on the wiki.

https://github.com/ninject/ninject.extensions.conventions/wiki

treze
  • 3,159
  • 20
  • 21