我希望能够遍历CSV文件中的所有记录,并将所有好的记录添加到一个集合中,并分别处理所有“坏的”记录。我似乎无法做到这一点,我想我一定很想念。
如果我尝试捕获BadDataException,则后续读取将失败,这意味着我无法继续读取该文件的其余部分-
while (true)
{
try
{
if (!reader.Read())
break;
var record = reader.GetRecord<Record>();
goodList.Add(record);
}
catch (BadDataException ex)
{
// Exception is caught but I won't be able to read further rows in file
// (all further reader.Read() result in same exception thrown)
Console.WriteLine(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
讨论的另一个选项是设置BadDataFound回调操作来处理它-
reader.Configuration.BadDataFound = x =>
{
Console.WriteLine($"Bad data: <{x.RawRecord}>");
};
Run Code Online (Sandbox Code Playgroud)
但是,尽管称为回调,但不良记录仍然会出现在我的“良好列表”中
在将其添加到列表之前,有什么方法可以查询读者以查看记录是否良好?
对于此示例,我的记录定义为-
class Record
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age …Run Code Online (Sandbox Code Playgroud) 我希望能够访问内置的 IoC 容器(IServiceProvider我相信)。
我知道在代码中访问它通常是不好的做法,我们应该允许框架将所需的任何依赖项注入到控制器之类的东西中。
我对此的具体应用是我正在使用另一种产品Hangfire。该框架本身实例化对象。为了将依赖项注入到这些对象中,您需要重写JobActivator类并在那里引用您自己的容器。
这个问题展示了如何创建一个新的容器用于测试目的,但我想访问我已经设置的容器,而不必重复它。使用像 Autofac 这样的 DI 框架,您可以在添加所有服务后构建容器时访问容器。
有人可以帮忙吗?