0

我有以下问题:

我有一堂课,我通过 DI 注入 Logger。

但最后我想实例化这个类。

这是代码:

public class DokumentInhaltJson : SimpleValueObject<string>
{
    public readonly ILogger<DokumentInhaltJson> _logger;
    
    private DokumentInhaltJson(
        string value, ILogger<DokumentInhaltJson> logger) : base(value)
    {
        _logger = logger;
    }

    public static Result<DokumentInhaltJson> Create(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return Result.Failure<DokumentInhaltJson>("Error message 1");
        }

        try
        {
           JObject objectToValidate = JObject.Parse(value);
        }
        catch (Exception e)
        {
            return Result.Failure<DokumentInhaltJson>("Error message 2"));
        }

        return Result.Success(new DokumentInhaltJson(value));
    }
}

现在的问题是,new DokumentInhaltJson现在希望将记录器作为第二个参数。

我可以在这里做什么?

4

1 回答 1

1

我相信您正在尝试在您创建的类型中组合一个对象工厂。将您的工厂移动到它自己的类型并使用它来创建DokumentInhaltJson.

public class DokumentInhaltJson : SimpleValueObject<string>
{
    private string _value;

    public DokumentInhaltJson(string value)
    {
        _value = value;
    }
}

public class DokumentInhaltJsonFactory
{
    private readonly ILogger _logger;

    public DokumentInhaltJsonFactory(ILogger logger)
    {
        _logger = logger;
    }

    public Result<DokumentInhaltJson> Create(string value)
    {

        if (string.IsNullOrWhiteSpace(value))
        {
            _logger.LogError("Null");
            return Result.Failure<DokumentInhaltJson>(string.Format(ErrorMessages.Common_FeldDarfNichtLeerSein,
                                                                nameof(DokumentInhaltJson)));
        }

        try
        {
            JObject objectToValidate = JObject.Parse(value);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message);
            return Result.Failure<DokumentInhaltJson>(string.Format(ErrorMessages.Common_MussGueltigesJSONObjektSein,
                                                                nameof(DokumentInhaltJson)));
        }

        return Result.Success(new DokumentInhaltJson(value));
    }
}
于 2020-11-11T21:49:35.090 回答