DI에서 런타임 매개 변수를 사용하여 런타임에 다른 객체를 만들 때 객체 생성을 처리하는 가장 좋은 방법은 무엇입니까? 나는 잘 읽는 Mark Seemann's answer regarding using abstract factories을 읽었지만 내 질문에는 수많은 추상 팩토리가 어떤 명령이 호출되는지에 따라 다른 뷰 모델을 생성하는 데 필요한 시나리오가 필요합니다.MVVM, Dependency Injection & Runtime 객체 생성
예를 들어, 응용 프로그램에 대한
public interface IMainRepository { }
public interface IOtherRepository { }
서비스 레이어
public interface IMainService { }
public interface IOtherService { }
public class MainService : IMainService
{
public MainService(IMainRepository mainRepository)
{
if (mainRepository == null)
{
throw new ArgumentNullException("IMainRepository");
}
_mainRepository = mainRepository;
}
readonly IMainRepository _mainRepository;
}
public class OtherService : IOtherService
{
public OtherService(IOtherRepository otherRepository)
{
if (otherRepository == null)
{
throw new ArgumentNullException("IOtherRepository");
}
_otherRepository = otherRepository;
}
readonly IOtherRepository _otherRepository;
}
보기 모델
저장소 층 아래에 설명
public class MainViewModel
{
public MainViewModel(IMainService mainService, IOtherViewModelFactory otherViewModelFactory)
{
if (mainService == null)
{
throw new ArgumentNullException("IMainService");
}
_mainService = mainService;
if (otherViewModelFactory == null)
{
throw new ArgumentNullException("OtherViewModelFactory");
}
_otherViewModelFactory = otherViewModelFactory;
InitializeCommonds();
}
readonly IMainService _mainService;
readonly IOtherViewModelFactory _otherViewModelFactory;
public RelayCommand<int> CreateOtherViewModelCommand { get; set; }
void InitializeCommonds()
{
CreateOtherViewModelCommand = new RelayCommand<int>(CreateOtherViewModel);
}
void CreateOtherViewModel(int otherId)
{
var otherVM = _otherViewModelFactory.Create(otherId);
//Do other fantastic stuff...
}
}
public class OtherViewModel
{
public OtherViewModel(IOtherService otherService, int otherId)
{
if (otherService == null)
{
throw new ArgumentNullException("IOtherService");
}
_otherService = otherService;
_otherId = otherId;
}
readonly IOtherService _otherService;
readonly int _otherId;
}
보기 모델 공장
public class OtherViewModelFactory : IOtherViewModelFactory
{
public OtherViewModelFactory(IOtherService otherService)
{
if (otherService == null)
{
throw new ArgumentNullException("IOtherService");
}
_otherService = otherService;
}
readonly IOtherService _otherService;
public OtherViewModel Create(int otherId)
{
return new OtherViewModel(_otherService, otherId);
}
}
CreateOtherViewModelCommand
회원이 MainViewModel
에서 호출 될 때, IOtherViewModelFactory
추상적 인 공장 의존성이 OtherViewModel
보기 모델을 만드는 데 사용됩니다. MainViewModel
이 더 이상 복잡하지 않게되면 완벽하게 작동합니다. MainViewModel
안에 다른보기 모델 유형을 만드는 수많은 명령이있을 때 어떻게됩니까? 내가 이해할 때, 나는 그것들을 위해 다른 추상적 인 팩토리를 생성 할 필요가 있지만, 이러한 추상적 인 팩토리 의존성은 생성자 삽입을 통해 제공되기 때문에 생성자 팽창으로 이어지지 않을까? 다른 유형의 뷰 모델을 생성하기 위해 10 개의 다른 추상 팩터 리가 필요한 경우를 상상해보십시오! 달성하고자하는 것을 구현하는 더 좋은 방법이 있습니까? 감사.
나는 어떤 이유로 든 Ninject를 사용할 수 없다고 가정하고 이에 대한 적절한 대답을 알고 싶습니다. 그러나, 나는 Ninject를 살펴볼 것이다. – Bablo