AspNet Core DI:TryAdd 与 Add 用法 [英] AspNet Core DI: TryAdd vs Add usage

查看:23
本文介绍了AspNet Core DI:TryAdd 与 Add 用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Sources 有 ,如果TryAdd 版本已经在IServiceCollection 中注册,则它不会添加服务.但是文档没有提到这种方法.什么时候用?

Sources has comment that TryAdd version do not adds service if it is already registered in IServiceCollection. But docs doesn't mention this method. When it should be used?

推荐答案

通常,如果您有一个带有依赖项的库,您将创建 IServiceCollection 的扩展方法,您的库的使用者会在启动时调用该方法来连接默认依赖项.

Typically if you have a library with dependencies you would create an extension method of IServiceCollection that the consumer of you library would call from startup to wire up the default dependencies.

.TryAdd 在您的扩展方法中非常有用,当只应使用接口的一种实现时.然后,如果有人想要覆盖默认实现,他们可以在调用您的扩展方法之前注册它,并且由于他们的实现首先注册,因此 TryAdd 不会添加任何内容.

.TryAdd is useful inside your extension method when only one implementation of an interface should be used. Then if someone wants to override a default implementation they can register it before calling your extension method and since their implementation is registered first the TryAdd won't add anything.

如果在您的扩展方法中使用了 .Add,您仍然可以通过在调用您的扩展方法之后注册它们的实现来覆盖默认实现.但在这种情况下,仍然有多个实现注册,因此可以依赖 IFoo 的 IEnumerable 并获取所有已注册的实现.但是如果他们依赖 IFoo,他们只会得到默认的,即添加的最后一个.

If .Add is used in your extension method, one can still override the default implementation by registering their implementation after the call to your extension method. But in this case there are still multiple implementations registered so one could take a dependency on IEnumerable of IFoo and get all the implementations that have been registered. But if they take a dependency on IFoo they get just the default one ie the last one added.

这篇关于AspNet Core DI:TryAdd 与 Add 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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