假设我有一个类(class)
class Foo : FooBase {
public Foo(Settings settings, IDbRepository db)
: base(settings) {
this.db = db;
}
...
}
基本上 FooBase 通过构造函数接收设置并从配置文件加载一些配置。
然后我有实现 IDbRepository 的 MySQLRepository 类
class MySQLRepository : IDbRepository {
...
public MySQLRepository(IConfigurationRepository config) {
conn = new MySQLConnection(config.GetConnectionString());
}
...
}
在 Program.cs 中我有:
Foo foo = container.Resolve<Foo>();
问题在于 FooBase 的构造函数仅在加载所有其他依赖项后才会被调用。但在调用 FooBase 构造函数之前不会加载配置。
我的想法是创建 IDbRepository 和任何其他需要配置的接口(interface)的惰性实现。
这是个好主意吗? 如何使用 Unity 容器实现它?
最佳答案
您在寻找 Deferring the Resolution of Objects ?
class Foo : FooBase {
Lazy<IDbRepository> _db;
public Foo(Settings settings, Lazy<IDbRepository> db)
: base(settings) {
_db = db;
}
}
关于c# - Unity 容器 - 延迟注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36183220/