Autofac RegisterInstance与SingleInstance [英] Autofac RegisterInstance vs SingleInstance
问题描述
IProductRepositoryProxy ProductDataServiceProviderInstance = new ServiceProductDataProvider();
builder.RegisterInstance(ProductDataServiceProviderInstance).As<IProductRepositoryProxy>();
VS
builder.RegisterType<ServiceProductDataProvider>().As<IProductRepositoryProxy>().InstancePerRequest();
我在这里从前员工那里看到了这段代码,想知道这家伙是否想要注册.SingleInstance()行为.
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();
是否通过RegisterInstance手动更新ServiceProductDataProvider而不是Register .SingleInstance()??
Is the manual newing-up of the ServiceProductDataProvider with RegisterInstance not the same as the Register .SingleInstance() ??
推荐答案
是否通过RegisterInstance手动更新ServiceProductDataProvider而不是Register .SingleInstance()??
Is the manual newing-up of the ServiceProductDataProvider with RegisterInstance not the same as the Register .SingleInstance() ??
RegisterInstance
允许您在 AutoFac 中注册一个实例.
The RegisterInstance
allows you to register a single instance in AutoFac.
RegisterInstance
和RegisterType
+ SingleInstance
方法之间的区别在于,RegisterInstance
方法允许您注册不是由 Autofac 构建的实例.
The difference between RegisterInstance
and RegisterType
+ SingleInstance
methods is that the RegisterInstance
method allows you to register an instance not built by Autofac.
但是两种解决方案都将导致在 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();
这篇关于Autofac RegisterInstance与SingleInstance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!