问题
Why and when should we use PreserveExistingDefaults during autofac registration?
I have read it's uses form Autoface docs: http://docs.autofac.org/en/latest/register/registration.html
But my question is, when is the case we will register multiple implementation with single interface.
Can anybody give some example from real time.
回答1:
It can be use when you want to register a new implementation without changing the default one. When you register multiple registration for a single interface, Autofac will resolve all of them when you try to register IEnumerable<IService>
Let say you have 2 implementations of IService
interface IService { }
class Service1 : IService { }
class Service2 : IService { }
If you register them like this :
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Service1>().As<IService>();
builder.RegisterType<Service2>().As<IService>().PreserveExistingDefaults();
IContainer container = builder.Build();
IService service = container.Resolve<IService>(); // will be Service1
List<IService> services = container.Resolve<IEnumerable<IService>>().ToList();
services[0]; // => Service1
services[1]; // => Service2 or the opposite, there is no warranty on the order
You will obtain Service1
when you resolve IService
but you will resolve both of them when you resolve IEnumerable<IService>
By the way, it is really exceptional to use it. I don't remember having ever used it. It is always simpler to use Named and Keyed services
来源:https://stackoverflow.com/questions/29891744/uses-of-preserveexistingdefaults