带有字符串参数的工厂方法

Factory method with string argument

在 DryIoc 中,如何将字符串参数传递给工厂方法?

在 Wiki 中,有一个关于如何传递另一个已注册 class 的示例,但我似乎无法弄清楚如何传递字符串。

鉴于以下情况:

public interface MyInterface
{
}

public class MyImplementationA : MyInterface
{
    public MyImplementationA(string value) { }
}

public class Factory
{
    public MyInterface Create(string value)
    {
        return new MyImplementationA(value);
    }
}

public class MyService1
{
    public MyService1(MyInterface implementation) {  }
}

class Program
{
    static void Main(string[] args)
    {
        var c = new Container();
        c.Register<Factory>(Reuse.Singleton);
        c.Register<MyInterface>(Reuse.Singleton, made: Made.Of(r => ServiceInfo.Of<Factory>(),
            f => f.Create("some value") //How do I pass a string to the factory method?
        ));

        c.Register<MyService1>();

        var a = c.Resolve<MyService1>();
    }
}

如果你想为特定的依赖注入一个字符串值,你可以这样做:

c.Register<Factory>(Reuse.Singleton);
c.Register<MyInterface>(Reuse.Singleton, 
    made: Made.Of(r => ServiceInfo.Of<Factory>(),
           // Arg.Index(0) is a placeholder for value, like {0} in string.Format("{0}", "blah")
            f => f.Create(Arg.Index<string>(0)), 
            requestIgnored => "blah or something else"));

这里是 how to provide Consumer type to log4net logger.

上 wiki 中的类似示例

另一种方式是c.RegisterInstance("value of blah", serviceKey: ConfigKeys.Blah);.

或者您可以使用 FactoryMethod 注册来注册字符串提供程序,以获取计算值、惰性值或任何值。为清楚起见,带有属性注册的示例:

[Export, AsFactory]
public class Config
{
    [Export("config.blah")]
    public string GetBlah()
    { 
      // retrieve value and
      return result;    
    }
}

// In composition root:
using DryIoc.MefAttributedModel;
// ...
var c = new Container().WithAttributedModel();
c.RegisterExports(typeof(Config), /* other exports */);