이건 오히려 강의같은거보다 이 홈페이지가 더 설명이 좋다
https://learn.microsoft.com/ko-kr/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-10.0
ASP.NET Core에서 종속성 주입
ASP.NET Core에서 종속성 주입을 구현하는 방법 및 사용 방법에 알아봅니다.
learn.microsoft.com
public interface IMyDependency
{
void WriteMessage(string message);
}
메서드 정의하고
public class MyDependency : IMyDependency
{
public void WriteMessage(string message)
{
Console.WriteLine($"MyDependency.WriteMessage Message: {message}");
}
}
구체적인거 구현
builder.Services.AddScoped<IMyDependency, MyDependency>();
Program.cs에 이거 추가하고
public class Index2Model : PageModel
{
private readonly IMyDependency _myDependency;
public Index2Model(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void OnGet()
{
_myDependency.WriteMessage("Index2Model.OnGet");
}
}
이런식으로 생성자 만들어버리고
현재 프로젝트에서는
CreateUser 메서드 정의
namespace BusinessLayer.Services
{
public interface ILoginService
{
public Task CreateUser(CreateUserDTO createUserDTO);
}
}
여기서 구체적인 형식 구현
namespace BusinessLayer.Services
{
public class LoginService : ILoginService
{
ILoginMapper loginMapper;
public LoginService(ILoginMapper mapper)
{
loginMapper = mapper;
}
public async Task CreateUser(CreateUserDTO createUserDTO)
{
try
{
//DTO와 Entity 변경
var configuration = new MapperConfiguration(cfg => cfg.CreateMap<CreateUserDTO, USER>(), NullLoggerFactory.Instance);
// Perform mapping
Mapper mapper = new Mapper(configuration);
USER user = mapper.Map<CreateUserDTO, USER>(createUserDTO);
await loginMapper.Create(user);
}
catch (Exception ex){ }
}
}
}
Program.cs에서
builder.Services.AddTransient<ILoginService, LoginService>(); //알아서 객체 생성하고 소멸시켜줌
이거 추가.
여기선 AddTransient를 사용하고
저기 페이지에서는 AddScoped를 사용했는데
이 두개의 차이는 뭘까?
https://ddochea.tistory.com/230
[ASP.NET Core] AddSingleton(), AddScoped(), AddTransient() 차이점 - 2
해당 포스트 작성하기 약 2년 전, ASP.NET Core 에서 3가지 생명주기에 대해 정리한 적이 있었다. [ASP.NET Core] AddSingleton(), AddScoped(), AddTransient() 차이점 - 1 :: 또치의 삽질 보관함 (tistory.com) [ASP.NET Core] A
ddochea.tistory.com
이분이 아주 자세히 설명해주시고 있다
AddSingleton의 경우는 클라이언트(보통 웹브라우저)의 접속상태에 관계없이, 웹 서비스 시작 때 생성되서, 웹 서비스가 종료될때까지 유지된다. Singleton이란 이름에 걸맞게, 클라이언트가 아무리 많이 붙어도 오직 1개의 서비스만 존재하게 된다.
AddScoped는 클라이언트의 Request 시작부터, Response 종료까지 유지된다. 각 클라이언트마다 존재하므로, 연결되는 클라이언트 수 만큼 존재하게 될 수 있다.
AddTransient는 의존성 주입한 객체마다 독립적인데, 그냥 간단한 교육용 예제 서비스에선 AddScoped와 구분이 잘 안갈 수 있을 것이다.
일단은 이렇게만 알고있고 다시 공부해보자