Kisa dependency injection ye, e poukisa .NET ak Spring itilize l tout kote?
posée 2 months ago160 vuesht
Nan tout tutorial .NET ak Spring, mwen wè konstriktè ki resevwa sèvis (IUserService userService) olye pou klas la kreye yo ak new. Poukisa?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
1 réponse
Dependency injection (DI) vle di: yon klas pa kreye depandans li yo limenm, li resevwa yo nan konstriktè a.
// San DI: klas la mare ak yon imèl reyèl, difisil pou teste
public class Enskripsyon {
private readonly SmtpMailer _mail = new SmtpMailer();
}
// Ak DI
public class Enskripsyon(IMailer mail) {
public Task Enskri(string imel) => mail.Voye(imel, "Byenvini!");
}
// Program.cs
builder.Services.AddScoped<IMailer, SmtpMailer>();
Avantaj yo: 1. Tès: nan tès ou pase yon FakeMailer, kidonk pa gen imèl reyèl k ap pati. 2. Chanjman fasil: ou ka chanje SmtpMailer pou ResendMailer nan yon sèl liy. 3. Framework la jere lavi objè yo (Singleton, Scoped pa rekèt, Transient).
Se menm lide a nan Spring (@Service + konstriktè) ak nan NestJS.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.