author: @ScottWeinstein title: IoC crash course footer: @ScottWeinstein subfooter: Lab49 presdate: 4/19/2011
- Why IoC
- Before and After
- Lifetime management
- IoC containers were create to solve problems with the classic application architectures
- Sharing configuration info
- The containment model means that IDisposability infects everthing
- Static global state
- The singleton anti-pattern
- Implicit shared static global state
- The config
- High coupling
- Hard to manage late bindings
- Plethora of custom factory classes to address the above
- Controller creates the model
- Model creates the DB connection
- which reaches out and gets it's connection string
- And they all implement IDisposable
- A bit more setup code, but in return, much simpler implementations
- Built-in flexibility to send in replacement implementations
- No more shared global state
Using Autofac...
- Register the container
- Controllers just ask for what they need
- Insulated from changes - look how the model is simpler, but has added more dependencies
builder.Register<DBEntities>(ctx => new DBEntities(ctx.Resolve<Config>().ConnectionString));
builder.Register<HttpContextBase>(ctx => FakeHttpContext());
When does my stuff get cleaned up?
With MVC apps, at the end of each request (by default)
Can override in many ways, .SingleInstance()
and Owned<T>
are two methods.
Let's look at AdvancedModel and LifetimeManagementModel
- WCF - similar model to MVC
- WPF/Silverlight - fine w/ ViewModel first frameworks, such as Caliburn.* If you're coding View-first, integrating IoC can be hard
- Setups can get complex
- Resolution failure is at runtime, exceptions messages can be... obscure
https://github.com/ScottWeinstein/IoC-Demos
- Install pandoc
- msbuild Demos.sln
- pandoc -t slidy -s .\README.md -o pres.html