【发布时间】: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<Service> 替换container.RegisterInitializer<IService>?
如果我这样做,则不会调用此初始化代码。
更一般地说,有没有什么方法可以在没有显式类型转换的情况下实现我想要的?如果我们可以将初始化链接到具体的类而不是接口,那就太好了。
【问题讨论】:
标签: dryioc