Dependency Injection with Autofac – Getting Started
Dependency Injection with Autofac – Constructor Injection
Dependency Injection with Autofac- Modules Feature
In this this blog we are going to learn about Registration ordering in Autofac. If you register same interface multiple times then by default the last registration will be preserved. So when you resolve things it will be resolved by last registration. You can also prevent that via “PreserveExistingDefaults” method which is a second behaviour where first registration will be preserved. We will look both in details in this post.
After creating a Employee class following is a code for my console application.
If you see code carefully, The important thing is two functions “DefaultBehaviour” and “AnotherBehaviour”. First function I’ve register two employee object one by one then. I tried to resolve employee object and with the help of "PrintEmployee" method I have printed Employee object. Here I’ve used default behaviour so it will print secondEmployee as last registration will be resolved.
While in “AnotherBehaviour” function, I have used “PreserveExistingDefaults” function while registering secondEmployee object. So it will preserve first registration. So when you resolve object it will resolve first registration. So when you print employee object with “PrintEmployee” method it will print firstEmployee object.
When you run this console application. Following will be output as expected.
That’s it. Hope you like it. Stay tuned for more!.
You can find complete source code this Autofac series on Github at - https://github.com/dotnetjalps/AutofacSamples