Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two ways of registering an instance in autofac

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.

like image 648
SteveM Avatar asked Nov 03 '22 21:11

SteveM


1 Answers

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.

like image 57
Peter Lillevold Avatar answered Nov 15 '22 05:11

Peter Lillevold