![](/img/trans.png)
[英]Dependency injection has no value for non-static class and static method in c#
[英]How to run non static method from static inside single class and use dependency injection C#
我试图从静态运行非静态方法并在非静态方法中使用依赖注入。 (我试图在一个班级中做到这一点)
我的代码如下所示:
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();
}
}
正如你从代码中了解到的,当我写“Tokens t = new Tokens();”时这段代码使用了构造函数而没有导入存储库。 该怎么办? 我可以在单个课程中修复它吗?
谢谢
PS如果问题很愚蠢,我很抱歉
静态和依赖注入不能很好地配合使用。
保持Tokens
作为实例类并抽象它
public interface ITokenService {
Task<string> GenerateJwt();
}
以便它可以作为依赖项注入。
从抽象派生Tokens
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();
}
}
现在您可以访问所需的成员作为依赖项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.