问题描述
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();
ServiceProductDataProvider 与 RegisterInstance 的手动更新是否与 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!