简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM