只是想知道是否有人在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.
更多推荐
通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项
发布评论