在使用運行時參數在運行時創建不同對象的DI中,處理對象創建的最佳方式是什麼?我已經閱讀Mark Seemann's answer regarding using abstract factories這工作得很好,但我的問題涉及一個場景,根據調用哪個命令,需要大量抽象工廠來創建不同的視圖模型。MVVM,依賴注入和運行時對象創建
例如,對於應用程序描述如下
庫層
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
中有許多其他命令創建其他視圖模型類型時會發生什麼?據我瞭解,我需要爲這些創建其他抽象工廠,但不會導致構造函數膨脹,因爲所有這些抽象工廠依賴項都是通過構造函數注入提供的?想象一下,我需要十個不同的抽象工廠來創建不同類型的視圖模型!有沒有更好的方法來實現我想要實現的目標?謝謝。
假設我無法使用Ninject的任何東西,我很想知道這個適當的答案。不過,我會看看Ninject。 – Bablo