简体   繁体   中英

How to run non static method from static inside single class and use dependency injection C#

I am trying to run non static method from static and use dependency Injection inside non static method. (I am trying to do this inside one class)

My code looks like this:

public class Tokens
{
    private IRefreshTokenRepository refreshTokenRepository;

    public Tokens(IRefreshTokenRepository refreshTokenRepository)
    {
        this.refreshTokenRepository = refreshTokenRepository;
    }

    // I understand that problem is there, but I should to write this
    //constructor because otherwise I can not use class variable in static method 
    public Tokens()
    {
    }


    public static async Task<string> GenerateJwt()
    {
        RefreshToken rf = new RefreshToken{...};

        Tokens t = new Tokens();
        t.StoreRefToken(rf);

        return JsonConvert.SerializeObject(...);
    }


    public async void StoreRefToken(RefreshToken reft)
    {
        this.refreshTokenRepository.InsertRefreshToken(reft);
        await refreshTokenRepository.SaveAsync();
    }


}

As you understand from code, when I wrote "Tokens t = new Tokens();"this code had used constructor without importing repository. What to do? Can I fix it inside single class?

Thank you

PS if question is silly I'm sorry

Static and Dependency Injection do not play well together.

Keep Tokens as an instance class and abstract it

public interface ITokenService {
    Task<string> GenerateJwt();
}

so that it can be injected as a dependency.

derive Tokens from the abstraction

public class Tokens: ITokensService {
    private readonly IRefreshTokenRepository refreshTokenRepository;

    public Tokens(IRefreshTokenRepository refreshTokenRepository) {
        this.refreshTokenRepository = refreshTokenRepository;
    }

    public async Task<string> GenerateJwt() {
        RefreshToken rf = new RefreshToken{...};

        await StoreRefToken(rf);

        return JsonConvert.SerializeObject(...);
    }

    private async Task StoreRefToken(RefreshToken reft) {
        this.refreshTokenRepository.InsertRefreshToken(reft);
        await refreshTokenRepository.SaveAsync();
    }
}

Now you have access to the desired members where ever it is needed as a dependency

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM