Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac RegisterInstance vs SingleInstance

IProductRepositoryProxy ProductDataServiceProviderInstance = new ServiceProductDataProvider(); builder.RegisterInstance(ProductDataServiceProviderInstance).As<IProductRepositoryProxy>(); 

VS

builder.RegisterType<ServiceProductDataProvider>().As<IProductRepositoryProxy>().InstancePerRequest(); 

I saw this code from an ex-employee here and wonder if the guy wanted to register a .SingleInstance() behavior.

builder.RegisterType<ServiceProductDataProvider>().As<IProductRepositoryProxy>().SingleInstance(); 

Is the manual newing-up of the ServiceProductDataProvider with RegisterInstance not the same as the Register .SingleInstance() ??

like image 490
Elisabeth Avatar asked Jul 23 '15 08:07

Elisabeth


People also ask

Does Autofac use reflection?

You register components with Autofac by creating a ContainerBuilder and informing the builder which components expose which services. Components can be created via reflection (by registering a specific .

Which constructor does Autofac use?

For resolution part here is the quote from documentation: "Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container" (see here).


1 Answers

Is the manual newing-up of the ServiceProductDataProvider with RegisterInstance not the same as the Register .SingleInstance() ??

The RegisterInstance allows you to register a single instance in AutoFac.

The difference between RegisterInstance and RegisterType + SingleInstance methods is that the RegisterInstance method allows you to register an instance not built by Autofac.

But both solution will result in registering a singleton in Autofac.

By the way, both registration are equivalent in the following code sample

var instance = GetInstanceFromSomewhere();   builder.RegisterInstance<IService>(instance);  builder.Register(c => instance).As<IService>().SingleInstance();  
like image 118
Cyril Durand Avatar answered Oct 05 '22 01:10

Cyril Durand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!