c# – Autofac RegisterInstance vs SingleInstance

前端之家收集整理的这篇文章主要介绍了c# – Autofac RegisterInstance vs SingleInstance前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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()?

解决方法

Is the manual newing-up of the ServiceProductDataProvider with RegisterInstance not the same as the Register .SingleInstance() ??

RegisterInstance允许您在AutoFac中注册一个实例.

RegisterInstance和RegisterType SingleInstance方法的区别在于RegisterInstance方法允许您注册一个非Autofac构建的实例.

但是这两种解决方案都将导致在Autofac中注册单例.

顺便说一句,两个注册在下面的代码示例中是等效的

var instance = GetInstanceFromSomewhere(); 

builder.RegisterInstance<IService>(instance); 
builder.Register(c => instance).As<IService>().SingleInstance();
原文链接:https://www.f2er.com/csharp/96942.html

猜你在找的C#相关文章