有时我需要在课程中获取一些构建信息。我不是指对其他对象的引用(将被注入),而是指保存唯一信息的字符串(例如)。
这样,我需要在 DI 容器初始化期间创建一个 InjectedRepositoryPath 实例并注册该实例。但是,我需要为每个类创建这样一个唯一的配置对象。
当然,我可以解析 RepositryFactory 而不是 Repository 对象,这样工厂就会要求我提供路径:
// 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 容器初始化期间创建一个 InjectedRepositoryPath 实例并注册该实例。但是,我需要为每个类创建这样一个唯一的配置对象。
当然,我可以解析 RepositryFactory 而不是 Repository 对象,这样工厂就会要求我提供路径:
class RepositoryFactory
{
Repository Create( string path ) { ... }
}
但是,这只是为单例对象设计的一个工厂...
或者,最后,由于路径将从配置文件中提取,我可以跳过传递字符串并在我的构造函数中读取配置(这可能不是最优的,但可行):
class Repository
{
public Repository( InjectedObject injectedObject )
{
// Read the path from app's config
}
}
你最喜欢的方法是什么?对于非单例类,您需要使用Init()
或工厂解决方案,但对于单例作用域对象呢?