.Net Core DI对我不起作用,并引发Null引用异常



我是.net核心的新手,需要您的帮助。下面是我的实现,不工作

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核心类库中

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接口在域类库中,其实现在基础设施库中,并且根据DDD原则,域不引用基础设施接口。

我上面做错了什么,以及如何修复空引用异常。

对不起,我是.net核心和.net核心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方法中,您可以通过serviceProviderDI Container对象进行调用,您可以从该Container中获取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;
}

最新更新