【问题标题】:DryIoc call service method upon resolutionDryIoc 在解析时调用服务方法
【发布时间】:2019-06-25 00:12:23
【问题描述】:

如何让 DryIoc 像往常一样解析 Service,然后立即让它使用一些特定参数调用其 Adjust( int ) 方法?

更新:根据dadhi提供的建议,代码改为使用RegisterInitializer

public interface IMaster
{
  void Run( int val );
}
public class Master : IMaster
{
  public Master( IService service )
  {
    service_ = service;
  }
  public void Run( int val )
  {
    service_.Execute( val );
  }

  private readonly IService service_;
}

public interface IService
{
  void Execute( int val );
}

public class Service : IService
{
  public void Adjust( int state ) // This method does not belong to the interface
  {
    Console.WriteLine( "Service state is adjusted with {0}", state );
    state_ = state;
  }

  public void Execute( int val )
  {
    var result = val + state_;
    Console.WriteLine( "Service execution resulted in {0}", result );
  }

  private int state_;
}

static void Main( string[] args )
{
  var container = new Container();

  container.Register<Service>( Reuse.Singleton );
  container.RegisterInitializer<IService>( ( service, resolver ) =>
                                           { // Casting type down is a bad idea.
                                             ( (Service)service ).Adjust( 5 );
                                           } );

  container.Register<IMaster, Master>( Reuse.Singleton,
                                       Parameters.Of.Type<IService>( typeof( Service ) ) );

  var master = container.Resolve<IMaster>();

  master.Run( 10 );
}

上面的代码使用了类型转换,首先,它很脏,可以被我们的代码质量标准阻止。

其次,可能会发生另一个注册,将IService映射到AlternativeService,这与Adjust方法无关。

所以问题是为什么我不能用container.RegisterInitializer&lt;Service&gt; 替换container.RegisterInitializer&lt;IService&gt;? 如果我这样做,则不会调用此初始化代码。

更一般地说,有没有什么方法可以在没有显式类型转换的情况下实现我想要的?如果我们可以将初始化链接到具体的类而不是接口,那就太好了。

【问题讨论】:

    标签: dryioc


    【解决方案1】:

    你可能需要RegisterInitializer方法。

    【讨论】:

    • 我尝试了 RegisterInitializer 但并没有立即意识到除了常规注册之外还必须调用它而不是代替常规注册。我的愚蠢错误。
    • 在正确调用 RegisterInitializer 之后出现了另一个问题。请查看更新后的代码和问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多