c# - How to configure dependency injection to allow only one instance of a class? -


during interview asked this.

we use in our project unity container dependency injection. gets initialized in globals.asax using bootstrapper.initialise();

my di

public class bootstrapper     {         public static iunitycontainer initialise()         {             var container = buildunitycontainer();             dependencyresolver.setresolver(new unitydependencyresolver(container));             return container;         }         private static iunitycontainer buildunitycontainer()         {             iunitycontainer container = new unitycontainer();             registerservice(container);             return container;         }         public static void registerservice(iunitycontainer container)         {             container.registertype<ilibraryservice, libraryservice>();         }      } 

there 2 questions .

  1. how many times di initialized through out project ?
  2. how configure dependency injection allow 1 instance of class?

this pretty basic question, goofing them badly. can suggest answers them. project environment vs2015,c#,mvc 5,unity ,repository pattern, ef.

1. di conatainer initialized once on when application started (application_start() event in global.asax).

2. asking containercontrolledlifetimemanager there overload of registertype method takes parameter instance of type lifetimemanager , instance created once , instance used every time, not create new object every time dependency resolution now:

container.registertype<ilibraryservice, libraryservice>(new containercontrolledlifetimemanager()); 

from msdn:

containercontrolledlifetimemanager registers existing object singleton instance. lifetime manager unity returns same instance of registered type or object each time call resolve or resolveall method or when dependency mechanism injects instances other classes. lifetime manager implements singleton behavior objects.

you can read more life time manager @ this msdn link


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -