Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity Container - Lazy injection

Lets say I have a class:

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?

like image 430
areller Avatar asked Apr 16 '26 12:04

areller


1 Answers

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;
  }
}
like image 122
Backs Avatar answered Apr 19 '26 00:04

Backs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!