What is the difference in autofac between these two registrations:
builder.Register(c => Instance).As<ISomeInterface>();
and
builder.RegisterInstance(Instance).As<ISomeInterface>().SingleInstance().ExternallyOwned();
where Instance is a (non-static) property of an autofac module in which the registration occurs, set by object initializer.
My reason for asking is that the former has been done in a piece of code I'm debugging and I'm getting some strange behavior as though there are two instances of ISomeInterface floating around. The functional need is for the Instance to live for the life of the container ( = life of application).
Please don't tell me that I should not do the first -- it's been done and I'm trying to understand what could go wrong/behave strangely as a result.
There is a significant difference here. With the instance registration, the reference in the Instance property will be passed on to Autofac once during container building. Future resolves will always get the same reference served up.
With the lambda variant, the lambda will be executed on each resolve, allowing the Instance property to return whatever reference is stored in the property at resolve time. Theoretically, you can change the contents of Instance during the lifetime of the application, thus serving a different reference to consumers that are resolved after the change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With