Kisa dependency injection ye, e poukisa .NET ak Spring itilize l tout kote?

asked 2 months ago157 viewsht

6

Nan tout tutorial .NET ak Spring, mwen wè konstriktè ki resevwa sèvis (IUserService userService) olye pou klas la kreye yo ak new. Poukisa?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

1 Answer

7
✓
✓ Accepted answer

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.

Sign in to tell others whether this worked.

answered 2 months ago

Sign in and verify your email to post an answer.