c# - Prism 7 DI中的Register vs RegisterInstance vs RegisterSingleton
问题描述
我正在尝试在 Prism 7 中为 DI 注册服务。我发现以下所有方法都有效,这是正确的方法吗?每个人的情况是什么?
public class AndroidInitializer : IPlatformInitializer
{
static OpenAppService openAppService = new OpenAppService();
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterInstance<IOpenAppService>(openAppService);
containerRegistry.Register<IFacebookLoginService, FacebookLoginService>();
containerRegistry.RegisterSingleton<IAppleSignInService, AppleSignInService>();
}
}
解决方案
First of all, what each of these methods does totally depends on the actual container used, especially when you go beyond the totally trivial things. That's probably the main cause why there's no documentation for this stuff.
That being said...
Register
says that the given service should be used when the given interface is injected, and that a new instance will be created for each single injection.RegisterSingleton
differs in that the same instance is used for all injections.RegisterInstance
is the same asRegisterSingleton
, but you have to provide an instance.
which is the correct way to do it? What is the case for each?
So, most of the time services are registered as singletons, because you want viewmodels to be able to communicate through the service. Example: the EventAggregator
- when one view models publishes an event, you expect others to receive it, which is only possible if they subscribe using the same instance as the publisher publishes on. A WCF client, though, doesn't need to be a singleton, because the communication happens on the server side.
You don't want to register instances because this mixes up registration and resolving, and you have to make absolutely sure that all dependencies of the instance have been registered already when creating the instance to register it (through a call to Resolve
, which in itself has a touch of evil). This is less of a problem if you register everything in one method, but becomes a lot more of a headache if you have multiple (interdependent) modules.
推荐阅读
- reactjs - 创建 React 应用程序时出现 NPM 和 Yarn Registry 问题
- jenkins - Jenkins 失败的屏幕截图
- ms-access - 用于更改组合框选择的 Win32 API 调用
- asp.net-web-api2 - 在 Web API 中提供 VB.net DLL 参考
- asynchronous - Netty Http 客户端分析。如何计算服务器响应时间?
- upgrade - 我正在尝试将 Grails 2.4 升级到 3.3.6 并且无法更改环境:从开发到测试。有人能帮我吗?
- docker - Windows 上的 Docker 构建未能建立新连接 Errno 11001 getaddrinfo failed
- python - 如何保存和重用 keras 模型的所有设置?
- python - 是否有任何 jenkins 插件可供开发人员轻松工作(替代 web2py)
- hibernate - 如何获取和/或设置谓词 CriteriaQuery 的参数?