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

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

问题描述

来源具有注释,如果 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天全站免登陆