Autofac RegisterInstance vs SingleInstance

Elisabeth picture Elisabeth · Jul 23, 2015 · Viewed 32.1k times · Source
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() ??

Answer

Cyril Durand picture Cyril Durand · Jul 23, 2015

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();