2017-05-22 87 views
0

以下示例将将应用程序配置实例的属性注册到容器中,下一个注册将使用该属性作为控制台编写器的构造函数。无法选择构造函数,其参数已从其他已注册的实例属性中解析出来

container.Register(
       Made.Of(r => ServiceInfo.Of<ApplicationConfiguration>(), f => f.SomeConfigurationValue), 
       serviceKey: nameof(ApplicationConfiguration.SomeConfigurationValue)); 

container.Register(
      Made.Of(
       () => new ConsoleWriter(
        Arg.Of<string>(nameof(ApplicationConfiguration.SomeConfigurationValue))))); 

然而,我们宁愿不登记在容器中的财产,但使用某种表达的直接选择注册的应用程序配置实例的属性。 我们希望有一些看起来像这样:

var typedMadeString = Made.Of(
       r => ServiceInfo.Of<ApplicationConfiguration>(), 
       f => f.Property); 
container.Register(
       Made.Of(
        () => new ConsoleWriter(Arg.Of<string>(typedMadeString)))); 

但是,这并不工作,下面的异常被抛出(我们预期):

Unable to resolve String {ServiceKey=DryIoc.Made+TypedMade`1[System.String]} 
as parameter "message" 
in DryIoc.Program.ConsoleWriter. 
Where no service registrations found 
and number of Rules.FallbackContainers: 0 
and number of Rules.UnknownServiceResolvers: 0 

有什么办法来实现这一目标?这是我们的样本班。我们只想注册这两类

private class ApplicationConfiguration 
    { 
     internal string SomeConfigurationValue => "Hello World"; 
    } 

    private class ConsoleWriter 
    { 
     private readonly string _message; 

     internal ConsoleWriter(string message) 
     { 
      this._message = message; 
     } 

     internal void Write(int times = 1) 
     { 
      for (var i = 0; i < times; i++) Console.WriteLine(this._message); 
     } 
    } 

回答

0
option 1: 

    c.Register<ConsoleWriter>(
     Made.Of(() => new ConsoleWriter(Arg.Index<string>(0)), 
     _ => c.Resolve<ApplicationConfiguration>().SomeConfigurationValue)); 

    option 2: if you change the ConsoleWriter constructor to public 

    c.Register<ConsoleWriter>(made: Parameters.Of 
    .Name("message", _ => c.Resolve<ApplicationConfiguration>().SomeConfigurationValue)); 

    option 3: the simplest, may be the best one to use. 

    c.RegisterDelegate<ConsoleWriter>(
     r => new ConsoleWriter(r.Resolve<ApplicationConfiguration>().SomeConfigurationValue)); 
相关问题