.Net Core DI 对我不起作用并抛出空引用异常

.Net Core DI Does Not Work For Me And Throws Null Reference Exception

我是 .net Core 的新手,需要您的帮助。下面是我的实现不起作用

Main.cs

    static void Main(string[] args)
    {

        var serviceProvider = new ServiceCollection()
            .AddLogging()
            .AddTransient<ICustomLogger, TextWriterLogger>()
            .BuildServiceProvider();

        StartAsyncTest(args);
    }

    public async static void StartAsyncTest(string[] args)
    {

        HttpAsyncTest.SetupCommand dto = new HttpAsyncTest.SetupCommand();
        HttpAsyncTest.ExecuteCommand executeCommand = new HttpAsyncTest.ExecuteCommand();
        var test = executeCommand.ExecuteAsync(new HttpAsyncTest(dto));
        await test;
    }

我的执行命令位于另一个名为 AsyncTest.Domain

的 .Net Core Class 库中
public partial class HttpAsyncTest : IValidEntity, IBuisnessEntity
{
    public HttpAsyncTest(SetupCommand dto)
    {
        HttpRequestContainers = new List<HttpAsyncRequestContainer>();
        this.Setup(dto);
    }

    private ICustomLogger _logger;
    public HttpAsyncTest(ICustomLogger logger)
    {
        _logger = logger;
    }

    async public Task ExecuteAsync(ExecuteCommand dto)
    {
         _logger.Log // throws null reference exception 
    }
}

ILogger 接口在域 class 库中,它的实现在基础结构库中,域不按照 DDD 原则引用基础结构。

我上面哪里做错了,我该如何修复空引用异常。

抱歉,我是 .net core 和 .net core DI 的新手,需要您的指导。

因为你没有使用DI Container创建实例,所以_logger字段会指向HttpAsyncTest对象中的NULL,而你没有赋值ICustomLogger 代码中的字段。

public partial class HttpAsyncTest : IValidEntity, IBuisnessEntity
{
    public HttpAsyncTest(SetupCommand dto,ICustomLogger logger)
    {
        HttpRequestContainers = new List<HttpAsyncRequestContainer>();
        _logger = logger;
        this.Setup(dto);
    }

    private ICustomLogger _logger;

    async public Task ExecuteAsync(ExecuteCommand dto)
    {
         _logger.Log;
    }
}

Main方法中,您可以通过serviceProvider DI容器对象调用,您可以从该容器中获取HttpAsyncTest对象,该容器将在您注册时创建一个对象。

static void Main(string[] args)
{

    var serviceProvider = new ServiceCollection()
        .AddLogging()
        .AddTransient<ICustomLogger, TextWriterLogger>()
        .AddTransient<SetupCommand>()
        .AddTransient<HttpAsyncTest>() 
        .BuildServiceProvider();
}

public async static void StartAsyncTest(ServiceProvider serviceProvider)
{

    HttpAsyncTest.ExecuteCommand executeCommand = new HttpAsyncTest.ExecuteCommand();
    var test = executeCommand.ExecuteAsync(serviceProvider.GetService<HttpAsyncTest>());
    await test;
}