【发布时间】:2011-01-18 20:49:09
【问题描述】:
有时我的课程需要获取一些构建信息。我不是在谈论对其他对象(将被注入)的引用,而是在谈论(例如)包含唯一信息的字符串:
// Scoped as singleton!
class Repository
{
public Repository( InjectedObject injectedObject, string path ) { ... }
}
如何注入这个字符串?一种可能是编写一个Init() 方法并避免对字符串进行注入:
class Repository
{
public Repository( InjectedObject injectedObject ) { ... }
public void Init( string path ) { ... }
}
另一种可能是将信息包装到一个可以注入的对象中:
class InjectedRepositoryPath
{
public InjectedRepositoryPath( string path ) { ... }
public string Path { get; private set; }
}
class Repository
{
public Repository( InjectedObject injectedObject, InjectedRepositoryPath path ) { ... }
}
这样我必须在我的 DI-Container 初始化期间创建一个InjectedRepositoryPath 的实例并注册这个实例。但我需要为每个类似的类提供这样一个独特的配置对象。
当然我可以解析RepositryFactory而不是Repository对象,所以工厂会问我路径:
class RepositoryFactory
{
Repository Create( string path ) { ... }
}
但同样,这是一个仅用于单例对象的工厂...
或者,最后,由于路径将从配置文件中提取,我可以跳过传递字符串并在构造函数中读取配置(这可能不是最佳的,但可能):
class Repository
{
public Repository( InjectedObject injectedObject )
{
// Read the path from app's config
}
}
你最喜欢的方法是什么?对于非单例类,您必须使用 Init() 或工厂解决方案,但是单例范围的对象呢?
【问题讨论】:
标签: dependency-injection inversion-of-control