在 Ninject 中使用工厂方法,我无法添加属性
我尝试使用 Ninject 注入 XmlReader。问题在于它是由工厂方法而不是构造函数创建的。我无法将 [Inject]
添加到 .NET Framework 中的代码中。现在我使用以下绑定来创建 XmlReader:
Bind<IXmlReader>()
.ToMethod(
x =>
XmlReader.Create(
(string) GetParameter(x, "inputUri"),
(XmlReaderSettings) GetParameter(x, "settings")))
.Named("definition");
private object GetParameter(IContext context, string name)
{
var parameters = (List<IParameter>) context.Parameters;
return (from p in parameters
where p.Name == name
select p.GetValue(context))
.FirstOrDefault();
}
我按如下方式使用它:
var reader = _kernel.Get<IXmlReader>("definition",
new Parameter("inputUri", FilePath, false),
new Parameter("settings", settings, false)))
但这段代码很糟糕。我可以用更漂亮更聪明的方式重写它吗?
I try to use Ninject to inject a XmlReader. The problem is that it is created by a factory method insted of a constructor. And I can't add a [Inject]
to code in the .NET Framework. Now I use following binding to create the XmlReader:
Bind<IXmlReader>()
.ToMethod(
x =>
XmlReader.Create(
(string) GetParameter(x, "inputUri"),
(XmlReaderSettings) GetParameter(x, "settings")))
.Named("definition");
private object GetParameter(IContext context, string name)
{
var parameters = (List<IParameter>) context.Parameters;
return (from p in parameters
where p.Name == name
select p.GetValue(context))
.FirstOrDefault();
}
And I use it as following:
var reader = _kernel.Get<IXmlReader>("definition",
new Parameter("inputUri", FilePath, false),
new Parameter("settings", settings, false)))
But this code is horrible. Can I rewrite it in any prettier smarter way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不是在做 DI,你是在做服务定位。
我不知道您的真实上下文,但我认为我会依赖
Func
并按如下方式进行绑定:-然后您在构造函数参数中声明注入的项目:
< Strike>有趣的是上面的
[Named]
是我自己的makey upey属性,您需要在绑定时执行条件方面。看看 dojo,它会告诉你如何做到这一点。有一个内置的NamedAttribute
(已经存在很多年了,不知道我在想什么)。如果注入工厂之类的东西对您的情况有用,那么接下来要考虑的是 Ninject。扩展.工厂。它以干净的方式处理大多数此类工厂要求。
You're not doing DI, you're doing Service Location.
I dont know your real context but I reckon I'd depend on a
Func<string,string,IXmlReader>
and do the Bind as follows:-Then you declare the injected item in your constructor args:
The fun bit is thatThere's a built in[Named]
above is my own makey upey attribute and you need to do the conditional aspect at bind time. Have a look at the dojo, it will show you how to do that bit.NamedAttribute
(and has been for ages, no idea what I was thinking).If something like injecting a factory is useful in your case, the next thing to look at is Ninject.Extensions.Factory. It handles most of these sorts of factory requirements in a clean manner.