3. Plan Inversion of Control (IoC) Dependency Injection pattern (DI) Dependency inversion principle Unity 2.0, StructureMap Guice, Spring Live ASP.NET MVC Demo
8. Terms Service —An object that performs a well-defined function when called upon Client —Any consumer of a service; an object that calls upon a service to perform a well-understood function
9. Terms Dependency —A specific service that is required by another object to fulfill its function. Dependent —A client object that needs a dependency (or dependencies) in order to perform its function.
12. Ex1:Composition public class SpellCheckerService{} public class TextEditor { private SpellCheckerService _spellCheckerService; public TextEditor() { _spellCheckerService = new SpellCheckerService(); } } class Program { static void Main(string[] args) { TextEditor textEditor = new TextEditor(); } }
15. Better approach Dependency Inversion High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. Robert C. Martin 1996
33. What’s bad You have to maintain factory or service locator The more combinations the more methods we have in factory. Your code knows about the specific factory or factory interface. This means that infrastructure logic is mixed with business logic. Factory may have states.
34. Service Locator Unfortunately, being a kind of Factory, Service Locators suffer from the same problems of testability and shared state.
37. Inversion of Control IoC – is a common characteristic of frameworks. According to Martin Fowler the etymology of the phrase dates back to 1988.
38. Dependency Injection DI is a kind of IoC Inversion of Control is too generic a term DI pattern – describes the approach used to lookup a dependency. Dependency resolution is moved to Framework.
51. Ex5: Dependency tree public interface IAdditionalDependency{} public class AdditionalDependency : IAdditionalDependency{} public class SpellCheckingService: ISpellCheckerService { public SpellCheckingService( IAdditionalDependency dependency){} }
52. Ex5: Dependency Tree UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckerService, SpellCheckingService>();container.RegisterType<IAdditionalDependency, AdditionalDependency>();TextEditor textEditor = container.Resolve<TextEditor>();
54. Ex6: Defining Injection Constructor public class TextEditor { private readonly ISpellCheckerService _spellCheckerService; [InjectionConstructor] public TextEditor(ISpellCheckerService spellCheckerService) { _spellCheckerService = spellCheckerService; } public TextEditor(ISpellCheckerService spellCheckerService,string name) { _spellCheckerService = spellCheckerService; } }
55. Ex7: Property Injection public class TextEditor { public ISpellCheckerService SpellCheckerService {get; set;} [Dependency] public ISpellCheckerService YetAnotherSpellcheckerService{get;set;} } UnityContainer container = new UnityContainer(); container.RegisterType<TextEditor>(new InjectionProperty("SpellCheckerService")); container.RegisterType<ISpellCheckerService, SpellCheckingService>(); TextEditor textEditor = container.Resolve<TextEditor>();
56. Ex8: Method call injection public class TextEditor { public ISpellCheckerService SpellcheckerService {get; set;} [InjectionMethod] public void Initialize (ISpellCheckerService spellcheckerService) { _spellCheckerService = spellcheckerService; } } UnityContainer container = new UnityContainer();//container.RegisterType<TextEditor>( new InjectionMethod("SpellcheckerService"));container.RegisterType<ISpellCheckerService, SpellCheckingService>();TextEditor textEditor = container.Resolve<TextEditor>();
57. Lifetime Managers TransientLifetimeManagerReturns a new instance of the requested type for each call. (default behavior) ContainerControlledLifetimeManagerImplements a singleton behavior for objects. The object is disposed of when you dispose of the container.
58. Lifetime Managers ExternallyControlledLifetimeManagerImplements a singleton behavior but the container doesn't hold a reference to object which will be disposed of when out of scope. HierarchicalifetimeManagerImplements a singleton behavior for objects. However, child containers don't share instances with parents.
59. Lifetime Managers PerResolveLifetimeManagerImplements a behavior similar to the transient lifetime manager except that instances are reused across build-ups of the object graph. PerThreadLifetimeManagerImplements a singleton behavior for objects but limited to the current thread.
68. Structure Map Example // Bootstrap Container container = new Container(x => x.For<ISpellCheckingService>(). Use<FrenchSpellCheckingService>());// Use TextEditor textEditor = container.GetInstance<TextEditor>();
69. Compared to Unity // Bootstrap UnityContainer container = new UnityContainer();container.RegisterType<ISpellCheckingService, EnglishSpellCheckingService>();// Using containerTextEditor textEditor = container.Resolve<TextEditor>();
70. Unity vsStructureMap Unity XML Configuration In Code configuration Attributes Benefits Easy code initialization Good documentation StructureMap XML Configuration In Code configuration Attributes Benefits Http & Session lifetime managers out of the box. Convenient XML configuration.
84. Sequence 1. Instantiate Proxy A 2. Instantiate B using Proxy A 3. Instantiate A using B from step 2 4. Initialize Proxy A with A Proxy A passes all requests to concrete A
90. Drawback If you want produced instances to be configured by general injection rules then your factories will depend on concrete injection framework. Google Guice has special interface to support such behavior but you’ll depend on googleGuice. No silver bullet.
92. History Spring project brought DI to mainstream. And thank Spring Guice appeared. Guice introduced new features and stimulated further Spring development. Now Guice and Spring are almost equal in DI field and which one to use depends on developer.
93. Spring Spring holds a huge DI market share. More than 80%. Proven enterprise solution DI is only a small part of its functionality Supports all major injection approaches Current version 3
94. Guice New kid on the block Introduced new features based on Java 5 support. ( e.g. Provider methods to circumvent type erasure) First-class error messaging. Very fast. Provides only DI Current version 2 ( Version 3 RC )
95. Spring or Guice In DI Spring and Guice are almost equal. Guice provides only DI DI in Spring is only a part of functionality Google extensively uses Guice Guice is trendy and developers just want to give it a try. So which framework to use heavily depends on project and concrete developer ( team)
96. Where to use Guice If you are sure that you do not need full Spring functionality and your project is not a huge enterprise level application then you can give it a try. Spring is standard de facto in the industry.