我有以下具有几个依赖项的基类:
public abstract class ViewModel
{
private readonly ILoggingService loggingService;
public ViewModel(
ILoggingService loggingService,
...)
{
this.loggingService = loggingService;
...
}
}
在我的派生类中,我不想重复这个基类构造函数中的所有参数,所以我这样做了:
public abstract class ViewModel
{
private readonly IUnityContainer container;
private ILoggingService loggingService;
...
public ViewModel(IUnityContainer container)
{
this.container = container;
}
public ILoggingService LoggingService
{
get
{
if (this.loggingService == null)
{
this.loggingService = this.container.Resolve<IUnityContainer>();
}
return this.loggingService;
}
}
...
}
现在我的派生类只需要将一件事传递给我的基类构造函数。我也有一个很好的效果,即仅在需要时才解决我的依赖关系。
但是,从那以后,我了解到传递 IOC 容器是一个坏主意。最好的替代设计模式是什么,请记住传入的许多服务已在我的 IOC 容器中注册为单例?