具有依赖性注入的类的新实例-C#

问题描述

我有以下问题:

我有一堂课,我通过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现在希望记录器作为第二个参数。

在这里可以做什么?

解决方法

我相信您正在尝试在创建的类型内合并对象工厂。将工厂移至其自己的类型,并使用该类型创建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));
    }
}