通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项 [英] Injecting a nullable dependency via constructor requires unity to register that nullable dependency

查看:101
本文介绍了通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否有人在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.

这篇关于通过构造函数注入可为空的依赖项需要统一注册该可为空的依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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