areller
areller

Reputation: 5238

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?

Upvotes: 3

Views: 6788

Answers (1)

Backs
Backs

Reputation: 24913

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;
  }
}

Upvotes: 7

Related Questions