Unity Container - Lazy injection

混江龙づ霸主 提交于 2019-12-14 03:57:10

问题


Lets say i have a clas

class Foo : FooBase {

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

  ...

}

Basically FooBase receives settings via constructor and loads some config from configuration file.

Then i have the class MySQLRepository which implements IDbRepository

class MySQLRepository : IDbRepository {

  ...

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

  ...

}

in Program.cs i have:

Foo foo = container.Resolve<Foo>();

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.

My idea is to create a lazy implementation of IDbRepository and any other interfaces that require configuration.

Is this a good idea? How do i implement it with Unity container?


回答1:


Are you looking for Deferring the Resolution of Objects?

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


来源:https://stackoverflow.com/questions/36183220/unity-container-lazy-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!