试图找出如何最好地处理以下场景:
假设有一个RequestContext
类,它依赖于一个外部服务,例如:
public class RequestContext : IRequestContext
{
private readonly ServiceFactory<IWeatherService> _weatherService;
public RequestContext(ServiceFactory<IWeatherService> weatherService, UserLocation location, string query)
{
_weatherService = weatherService;
...
我需要在最终实例化RequestContext
的类中引用哪种依赖项?它可以是ServiceFactory<IWeatherService>
,但那似乎不太对,或者我可以按照以下方式创建一个IRequestContextFactory
:
public class RequestContextFactory : IRequestContextFactory
{
private readonly ServiceFactory<IWeatherService> _weatherService;
public RequestContextFactory(ServiceFactory<IWeatherService> weatherService)
{
_weatherService = weatherService;
}
public RequestContext Create(UserLocation location, string query)
{
return new RequestContext(_weatherService, location, query);
}
}
然后通过构造函数注入传递IRequestContextFactory
。
这似乎是一个不错的方法,但这种方法的问题在于我认为它会阻碍发现(开发人员必须知道工厂并实现它,这并不明显)。
是否有更好/更易发现的方法我可能错过了?