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 .
- how many times di initialized through out project ?
- 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
Post a Comment