在 ASP.NET Core 中,依赖注入是由 built-in 的 DI 容器来实现的,该容器默认是不会注入空引用的。如果需要注入 null 值,可以使用 Nullable 类型。以下是一个示例:
public interface IFoo
{
void Bar();
}
public class Foo : IFoo
{
public void Bar()
{
// Implementation of Bar method
}
}
public class MyClass
{
public MyClass(IFoo foo)
{
foo?.Bar();
}
}
public static void Main(string[] args)
{
var serviceProvider = new ServiceCollection()
.AddScoped()
.BuildServiceProvider();
// pass null value
var myClass = serviceProvider.GetService();
}
在上面的代码中,MyClass 类的构造函数中注入了一个 IFoo 类型的实例,并在方法内部调用了 Bar() 方法,如果 IFoo 实例为 null,则不会调用 Bar() 方法。最后在 Main 方法中,使用 ServiceProvider.GetService