Unity容器 - 懒惰注射

are*_*ler 2 .net c# dependency-injection lazy-loading unity-container

让我们说我有一个clas

class Foo : FooBase {

  public Foo(Settings settings, IDbRepository db)
    : base(settings) {
      this.db = db;
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

基本上FooBase通过构造函数接收设置并从配置文件加载一些配置.

然后我有实现IDbRepository的类MySQLRepository

class MySQLRepository : IDbRepository {

  ...

  public MySQLRepository(IConfigurationRepository config) {
    conn = new MySQLConnection(config.GetConnectionString());
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

在Program.cs我有:

Foo foo = container.Resolve<Foo>();
Run Code Online (Sandbox Code Playgroud)

问题是只有在加载了所有其他依赖项之后才调用FooBase的构造函数.但是在调用FooBase构造函数之前不会加载配置.

我的想法是创建一个IDbRepository和任何其他需要配置的接口的惰性实现.

这是一个好主意吗?我如何使用Unity容器实现它?

Bac*_*cks 5

你在寻找推迟对象的分辨率吗?

class Foo : FooBase {
  Lazy<IDbRepository> _db;
  public Foo(Settings settings, Lazy<IDbRepository> db)
    : base(settings) {
    _db = db;
  }
}
Run Code Online (Sandbox Code Playgroud)