3

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?

3
  • 2
    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. what? are you trying to say? why is that? is that an issue of the registrations in your DI container? IConfigurationRepository is a dependency of MySQLRepository which is resolved as IDbRepository, which is a dependency of Foo - the dependency graph is pretty straight forward, which is why I don't get the issue you are facing ... (btw: IDbRepository is not connected to FooBase.ctor) Commented Mar 23, 2016 at 16:12
  • config.GetConnectionString() accesses the app configuration. However, the app configuration is loaded only at the BaseFoo constructor (i don't have access to that class). Unity resolves IDbRepository (and calls the constructor of MySQLRepository) before the constructor of BaseFoo is called. So basically, the MySQLRepository constructor which tries to load the connection string from configuration is called before the connection string is fetched from the app configuration (at the BaseFoo constructor). Commented Mar 23, 2016 at 16:19
  • 1
    Code with circular dependencies is very hard to reason about. It would be much better for people looking at the code later to remove circular dependency in more sensible way than attempt of lazy loading. Commented Mar 23, 2016 at 16:19

1 Answer 1

7

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.