Autofac RegisterInstance与SingleInstance的区别

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

VS

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

我在这里看到了一段代码,想知道这个人是否想要注册 .SingleInstance() 行为。

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

使用RegisterInstance手动更新ServiceProductDataProvider,是否等同于使用Register.SingleInstance()进行注册?

1个回答

93

使用 RegisterInstance 手动创建 ServiceProductDataProvider 实例,与使用 Register.SingleInstance() 注册方式是否相同?

RegisterInstance 方法允许你在 AutoFac 中注册单个实例。

RegisterInstance 方法与 RegisterType + SingleInstance 方法的区别在于,RegisterInstance 方法允许你注册一个不是由 Autofac 构建的实例。

但无论哪种方式,都会导致在 Autofac 中注册一个 singleton。

顺便说一句,在下面的代码示例中,这两种注册方式是等效的。

var instance = GetInstanceFromSomewhere(); 

builder.RegisterInstance<IService>(instance); 
builder.Register(c => instance).As<IService>().SingleInstance(); 

这段代码是否与您上面的两个.Register调用相同且等效?=> builder.RegisterType<ServiceProductDataProvider>().As<IProductRepositoryProxy>().SingleInstance(); 我使用了您没有提到的RegisterType。 - Elisabeth
1
@Elisa 不是严格等价的。使用 RegisterType + SingleInstance 解决方案,您可以在 Autofac 中注册一个单例(就像其他解决方案一样),但您不必提供实例,Autofac 将在第一次需要时构建它,而对于 RegisterInstanceAutofac 不会创建实例,它必须在注册过程中创建。 - Cyril Durand
好的,但从技术上讲,最终它是相同的,一个Singleton实例共享整个应用程序生命周期,直到IIS关闭... - Elisabeth
2
@Elisa。是的。只要容器还在运行,实例就会被共享。 - Cyril Durand
它是一个单例实例,而不是单态模式。单态模式禁止创建该组件的新实例(例如使用私有构造函数)。 - dkokkinos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接