通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项

编程入门 行业动态 更新时间:2024-10-26 20:32:19
本文介绍了通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

只是想知道是否有人在Unity(作为IoC容器)中有这种情况,其中该类具有两个注入的依赖项(接口),其中一个依赖项可以为null.例如:

Just wondering if anyone had this scenario with Unity(as an IoC container) where the class has two injected dependencies(interfaces) where one dependency can be null. For example:

public MyServiceDll(IRepository repository, ICanBeNullDependency canBeNullDependency = null) { _repository = repository; _canBeNullDependency = canBeNullDependency; }

ICanBeNullDependency来自另一个程序集. MyServiceDll是另一个程序集. Web API引用MyServiceDll并将其接口注入其中一个控制器中. ICanBeNullDependency可以为null,因此我不需要在unityconfig.cs中注册此接口的实现,但是当调用控制器时,它将错误提示:

ICanBeNullDependency is from another assembly. MyServiceDll is another assembly. MyServiceDll is referenced by web api and injected its interface in one of the controllers. ICanBeNullDependency can be null so I don't need to register an implementation of this interface in unityconfig.cs but when the controller gets called it will error saying:

The current type, ICanBeNullDependency, is an interface and cannot be constructed. Are you missing a type mapping?

推荐答案

对于并非始终需要的依赖项,可以使用空对象模式.

For dependencies that are not always required, you can use the null object pattern.

public interface ICanBeNullDependency { void DoSomething(); } public class AcutallyDoSomething : ICanBeNullDependency { public void DoSomething() { Console.WriteLine("something done"); } } public class NullDoSomething : ICanBeNullDependency { public void DoSomething() { // Do nothing - this class represents a null } }

然后,如果要空状态",请注入null类的实例.

Then if you want a "null state", you inject an instance of the null class.

实际使变量为null的主要优点是您不需要在服务中使用任何条件逻辑来处理null,当然,它对DI友好.

The main advantage over actually making the variable null is that you don't need any conditional logic in your service to deal with a null, and of course it is DI-friendly.

更多推荐

通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项

本文发布于:2023-11-16 02:09:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600040.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!