Julia
Julia

Reputation: 19

New Instance of Class with Dependency Injection - C#

I have the following problem:

I have a class, where I inject Logger via DI.

But at the end I want to instantiate this class.

Here is the code:

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));
    }
}

The problem now is that new DokumentInhaltJson now wants the logger as a second parameter.

What can I do here?

Upvotes: 0

Views: 749

Answers (1)

Jerry
Jerry

Reputation: 1527

I believe you are attempting to combine an object factory within the type you are creating. Move your factory to it's own type and use that to create instances of 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));
    }
}

Upvotes: 1

Related Questions