在DI中,当使用运行时参数在运行时创建不同的对象时,处理对象创建的最佳方法是什么?我已阅读Mark Seemann's answer regarding using abstract factories但效果很好,但我的问题涉及一个场景,根据调用的命令,需要许多抽象工厂来创建不同的视图模型。
例如,对于下面描述的应用程序
存储库层
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
中有许多其他命令创建其他视图模型类型时会发生什么?据我了解,我还需要为那些创建其他抽象工厂,但这不会导致构造函数膨胀,因为所有这些抽象工厂依赖项都是通过构造函数注入提供的吗?想象一下,我需要十个不同的抽象工厂来创建不同类型的视图模型!有没有更好的方法来实现我想要实现的目标?感谢。