builder .Register(b => new F()) .As<IF>(); builder .Register(b => new E()) .As<IE>(); builder .Register(b => new D1()) .Named<ID>(SomeD1Name); builder .Register(b => new D2()) .Named<ID>(SomeD2Name); builder .Register((b,prms) => new C(b.Resolve<IE>(), prms.TypedAs<IF>())) .Named<IC>(CName); builder .Register((b,prms) => new B(b.Resolve<IF>(), b.ResolveNamed<IC>(CName, prms))) .As<IB>(); builder .Register(b => new A(b.Resolve<IE>(), b.ResolveNamed<ID>(SomeD1Name), b.ResolveNamed<ID>(SomeD2Name))) .As<IA>(AName); builder .Register(b => new Service(b.Resolve<IComponentContext>(), b.Resolve<IA>(), b.Resolve<IB>())) .As<IService>();
And that’s it.
Markdown | Result |
---|---|
*text* | text |
**text** | text |
***text*** | text |
`code` | code |
~~~ more code ~~~~ |
more code |
[Link](https://www.example.com) | Link |
* Listitem |
|
> Quote | Quote |
Autofac is a great DI container. I use it as my favorite one – I had some experience with Castle.Wi ndsor and Unity, but both them lost the competition (castle.Windsor is too complex and monolithic, Unity is too slooooow). Also I've heard about Ninject and StructureMap, but as far as I know Ninject is slower (but provides very good interface and structure, to work with) and StructureMap was not actively developing at the time of my evaluation (but they had new release in August[http://nuget.org/packages/structuremap], so it's worth to evaluate it again).
I use Autofac intensively in web projects (ASP/MVC), because it's extremely fast if you use it properly (with lambdas/expressions). Also it supportx modular approach (each component of the system might has it's own IoC module). And I like it for scoping support, so you could have application-wide scope, request0wide, transaction-wide and so on. Request-wide scope container is good place for UnitOfWork instance (for example, ORM context) and application-wide scope fits to "singletons", configuration objects or localization services.
I used StructureMap, NInject, Unity, Spring.NET and Autofac. Each has pros and cons, but I don't bother as long as IoC is leveraged in application. All of them have enough features for most of projects. At the same time getting used to any is deal of few days.
Thanks for posting. I think I disagree with your opening statement… "I call it “fun”, because it is very explicit and easy to understand. Reading though it makes it clear what dependencies are:" Consider verbose variables when trying to teach someone something. It is hard to get into your head to determine what b, IF, IE, IC, ID, or IA means… Comments about intent always help (intent, not what the code does. for example, a comment that reads "setting variable x to 1" is not helpful. A comment that reads "setting variable x to 1 because I am using it as a pseudo-Boolean, and when true that means process a finished, so call a service" is much more helpful)