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

poze 2 months ago155 gadeht

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?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

1 Repons

7
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 2 months ago

Sign in and verify your email to post an answer.