试图找出如何最好地处理以下情形:依赖注入和工厂
假设一个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
。
这似乎是一个很好的方法,但这种方法的问题是,我认为它阻碍了可发现性(开发人员必须了解工厂并实施它,这并不是很明显)。
我错过了更好/更容易发现的方式吗?
有趣的是,我没有想过直接注入RequestContext,因为它的参数在每个页面请求(ASP.NET MVC)上都会有所不同。使用NInject通过查看查询字符串来正确地为我实例化类是否是一个好主意?或者我会配置NInject使用返回实例的工厂,但在基本级别只需要注入RequestContext? – andreialecu 2010-06-10 13:11:49
我还不知道Ninject已经足够回答关于这个问题的细节了,但是如果它不直接支持这个,你可以使用注入到更高级别消费者的抽象工厂自己实现这个小部分。 – 2010-06-10 13:22:33