Unity容器-延迟注入 [英] Unity Container - Lazy injection

查看:70
本文介绍了Unity容器-延迟注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有个问题

class Foo : FooBase {

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

  ...

}

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

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

然后,我有了实现IDbRepository的类MySQLRepository

Then i have the class MySQLRepository which implements IDbRepository

class MySQLRepository : IDbRepository {

  ...

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

  ...

}



在Program.cs中的

我有:

in Program.cs i have:

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

问题在于FooBase的构造函数仅在加载所有其他依赖项之后才被调用。但是直到调用FooBase构造函数后,配置才会加载。

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.

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

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

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

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

推荐答案

您是否在寻找推迟对象的分辨率

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

这篇关于Unity容器-延迟注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆