在DryIoc中,如何将字符串参数传递给工厂方法?
在Wiki中,有关于如何传递另一个注册类的示例,但我似乎无法弄清楚如何传递字符串。
鉴于以下内容:
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>();
}
}
答案 0 :(得分:2)
如果要为特定依赖项注入字符串值,可以这样做:
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 */);