47
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() ??

trailmax
  • 34,305
  • 22
  • 140
  • 234
Elisabeth
  • 20,496
  • 52
  • 200
  • 321

1 Answers1

91

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(); 
Cyril Durand
  • 15,834
  • 5
  • 54
  • 62
  • Would this code be also the same and equivalent to your TWO .Register calls above? => builder.RegisterType().As().SingleInstance(); I use the RegisterType which you did not mention. – Elisabeth Jul 23 '15 at 09:02
  • 1
    @Elisa not strictly equivalent. With the `RegisterType` + `SingleInstance` solution, you register a singleton in *Autofac* (like the other solution) but you don't have to provide the instance, *Autofac* will build it the first time is required whereas for the `RegisterInstance` *Autofac* don't create the instance and it has to be created during the registration process – Cyril Durand Jul 23 '15 at 09:06
  • ok but in the end its technically the same a Singleton instance shared the whole application lifecycle until IIS goes down... – Elisabeth Jul 23 '15 at 09:56
  • 2
    @Elisa. Yes. As far as the container is live, the instance will be shared – Cyril Durand Jul 23 '15 at 11:33
  • Its a single instance its not a singleton. A Singleton prohibits creating a new instance of that component (e.g. with a private constructor) – dkokkinos Jan 18 '23 at 13:21