Autofac RegisterInstance与SingleInstance [英] Autofac RegisterInstance vs SingleInstance

查看:123
本文介绍了Autofac RegisterInstance与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.

RegisterInstanceRegisterType + 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆