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);
        }
    }
4

1 回答 1

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));
于 2017-05-22T06:39:33.183 回答