0

想知道是否有人有这种情况与Unity(作为IoC容器)类有两个注入依赖项(接口),其中一个依赖项可以为空。例如:通过构造函数注入可空的依赖需要统一注册可空的依赖

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

ICanBeNullDependency来自另一个程序集。 MyServiceDll是另一个程序集。 MyServiceDll被web api引用,并将其接口注入到其中一个控制器中。 ICanBeNullDependency可以为空,所以我并不需要注册此接口的实现在unityconfig.cs但是当控制器被调用时,它将错误说:

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

回答

2

对于依赖关系并不总是需要,可以使用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类的实例。

实际进行变量null的主要优势在于,您不需要任何条件逻辑来处理空值,当然这是DI友好的。

+0

我甚至会说“你***应该使用空对象模式。” – Steven