带参数的结构图解析类型
我有一个问题...... 以免说我有一个这样的类:
public class A: InterfaceA
{
private FileInfo _fileInfo = null;
public A(FileInfo fileInfo)
{
this._fileInfo = fileInfo;
}
...
}
和另一个:
public class B: InterfaceB
{
private A _classA = null;
public B(A classA)
{
this._classA = classA;
}
public void Do()
{
FileInfo fi = new FileInfo(...);
_classA.DoSomething();
}
}
现在,我已经设置了如下所示的 StructureMap 寄存器:
For<InterfaceA>().Use<A>();
For<InterfaceB>().Use<B>();
当我执行 B.Do() 时,结构映射将引发错误,因为没有 FileInfo 参数的注册表项。 A类的参数(FileInfo)是在B类中构造的; 我知道我可以这样做:ObjectFactor.GetInstance() 并传递参数,但我想要依赖注入而不是服务提供者。我希望当我执行 ObjectFactory.GetInstance() 时,构造整个对象图。
如何做到这一点?
I have a problem....
Lest say I have a class like this one:
public class A: InterfaceA
{
private FileInfo _fileInfo = null;
public A(FileInfo fileInfo)
{
this._fileInfo = fileInfo;
}
...
}
and another one:
public class B: InterfaceB
{
private A _classA = null;
public B(A classA)
{
this._classA = classA;
}
public void Do()
{
FileInfo fi = new FileInfo(...);
_classA.DoSomething();
}
}
Now, I have setup StructureMap registers like this:
For<InterfaceA>().Use<A>();
For<InterfaceB>().Use<B>();
and when I execute B.Do() structuremap will throw an error because there is no registry entry for FileInfo parameter.
The parameter of class A (FileInfo) is constructed in class B;
I know that I can do: ObjectFactor.GetInstance() and pass parameters, but I want Dependency injection not service provider. And I want that when I do ObjectFactory.GetInstance(), to construct entire object graph.
How to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Ctor 指令告诉 SM 使用哪些对象作为 Ctor 参数。
在此处了解有关 Ctor 参数的更多信息。
编辑:
如果在执行 B 中的 Do 方法之前不知道文件名,则必须推迟 A 对象的创建,直到执行 do 方法。为此,您可以使用手动编码或 Func/Lazy 工厂。
对于 Func 方法,您可以更改 B 以将 A 的 Func 作为 ctor 依赖项:
使用以下命令引导它:
You can use the Ctor instruction to tell SM what objects to use for the Ctor parameters.
Read more about Ctor arguments here.
Edit:
In case the file name is not known until the execution of the Do method in B, you have to postpone the creation of the A-object until the do method is executed. In order to do so you can use a factory, either hand coded or a Func/Lazy.
For a Func approach you can change your B to take a Func of A as ctor dependency:
Boot strap it using: