Ioc: Broad term. Prog style where framework or runtime control the program flow. For example, ASP.Net lifecycleDI – coined by Martin Folweris a set of software design principles and patterns that enable us to develop loosely coupled code. See pg. 42NOTE: Ioc nicely describes exactly what we’re trying to do.
See table page 16Late binding – replace services without recompile
SRP - an object should have only a single responsibilityOpen/Closed - open for extension, but closed for modificationLiskovSubstution Principle - objects in a program should be replaceable with instances of their subtypesInterface segregation principle - many client-specific interfaces are better than one general-purpose interface.Dependency Inversion principle - Depend upon Abstractions. Do not depend upon concretions.
Abstract class or interface. I’ll use the word interface for simplicity, but either will do.
Note, only the enemy when a volatile dependency. .Net BCL dependencies aren’t. new StringBuilder() is fine, unless for some reason it’s not. The amount of coupling in an application is loosely correlated to the number of times you see the new keyword in the codebase.
Pg 82 Each app should only have a single reference to each of the above methods. Why, config should be considered a single atomic action. Once resolved, consider the container read only. Be sure to release what you resolve. Naming convention from Castle Windsor.
Property: (aka setter – use when a good local default, but want to allow callers to provide alternative assemblies)
benefits on pg 68
TightlyCoupled project – HomeController.cs
HomeController alternative Index method
Common when attempting to make class testable without understanding DIBastard Injection 146
Embarrassing coupling problem? Let’s solve that withDependency Injection Cory House @housecor | bitnative.com
Watch for Volatilitynew StringBuilder() App specificnew List<T>() new User, Product, OrderSystem.Xml Non-deterministic DateTime.Now, File, Data Slow Remote service
Composition Root• Where the app “starts”• Classes are composed here• Keeps app unaware of the IoC container• Unique techniques for different techs
Composition RootTechnology Composition RootConsole App Main methodASP.NET MVC Call custom IControllerFactory in Global.asaxWCF ServiceHostFactory and a few other tricksASP.NET Web Forms Humble object or Service Locator in each aspx.cs
Injection Location1. Constructor2. Property3. MethodLocation Usage Benefits DrawbacksConstructor When possible Simple Tricky (some frameworks) Guarantees injection Object graph on startup ExplicitProperty Good local default Easy to understand Not simple to implementMethod Dependency Caller provides Limited applicability varies by method operation specific call context
Config Styles Mapping Advantages Disadvantages XML Config Late binding No compile-time checks Control Verbose Code Code Compile-time checks Must recompile Control IntellisenseAuto-Registration Rules Late binding Partial compile-time checks Automatic = Less work Less control Reinforces conventions Magic
Config Style SupportStyle Castle Windsor StructureMap Spring.Net Autofac UnityXML X X X X XCode X X X XAuto-registration X X X
ExplicitXML Code as Configuration Late Binding Early Binding Auto Registration Implicit
LifestylesLifestyle Description UsageSingleton Once on App startup. Most Thread safe, stateless, efficient. immutable, circuit breaker, in- memory cacheTransient Per Request. Least efficient. Default (most)Per Graph One instance of each Anywhere thread that resolves is dependency per thread the only consumer of the graph. Efficient alt to transient.Web Request One instance per web request Web app requests whenContext singleton won’t workThread Context Per threadSession Context Per sessionPooled Pool of ready objects Expensive to createScopedCustom
Lifestyle SupportLifestyle Castle StructureMap Spring.Net Autofac Unity WindsorSingleton X X X X XTransient X X X X XPer Graph X XWeb X X (X) XRequestContextThread X X XContextSession X (X)ContextPooled XScoped X XCustom X X X
WarningWindsor: SingletonStructureMap: TransientRelease transients or burn all RAM
Cross-cutting concernsTwo approaches:1. Dynamic Proxies2. IL Weaving
PostSharp Normal PostSharp .NetAttributes Compilation Compilation Assembly
AOP via attributes1. Modify compilation • PostSharp2. Custom runtime host • WCF • ASP.Net MVC • Unit testing frameworks
AOP via attributes• No special design effort • Code runs different from• Easy to spot since inline the code you wrote• Explicit since in context • Vendor lock-in • Attributes compiled with code = Tightly coupled. • Can’t vary the aspect independently of the implementation • Can’t use conventions
How do I choose a container?PerformanceLifetimesDocumentationAPISupportDynamic proxies
Summary1. Compose at composition root2. Prefer constructor injection, auto-registration3. Volatility? Think smoke detectors vs sockets
To Do• Remove references to data layer(s) in MVC project. Surprising that ploeh did it in his, but clearly a risky issue since it means others might tightly couple• Add checks in project to protect from bad refs.