Unity容器-延迟注入
让我们说我有个问题
class Foo : FooBase {
public Foo(Settings settings, IDbRepository db)
: base(settings) {
this.db = db;
}
...
}
基本上,FooBase通过构造函数接收设置,并从配置文件中加载一些配置。
Basically FooBase receives settings via constructor and loads some config from configuration file.
然后,我有了实现IDbRepository的类MySQLRepository
Then i have the class MySQLRepository which implements IDbRepository
class MySQLRepository : IDbRepository {
...
public MySQLRepository(IConfigurationRepository config) {
conn = new MySQLConnection(config.GetConnectionString());
}
...
}
在Program.cs中的
我有:
in Program.cs i have:
Foo foo = container.Resolve<Foo>();
问题在于FooBase的构造函数仅在加载所有其他依赖项之后才被调用。但是直到调用FooBase构造函数后,配置才会加载。
The problem is that the constructor of FooBase is called only after all other dependencies were loaded. but the configuration isn't loaded until the FooBase constructor is called.
我的想法是创建IDbRepository和需要配置的任何其他接口的惰性实现。
My idea is to create a lazy implementation of IDbRepository and any other interfaces that require configuration.
这是个好主意吗?
如何使用Unity容器实现它?
Is this a good idea? How do i implement it with Unity container?
您是否在寻找推迟对象的分辨率?
class Foo : FooBase {
Lazy<IDbRepository> _db;
public Foo(Settings settings, Lazy<IDbRepository> db)
: base(settings) {
_db = db;
}
}