StructureMap:具体类构造函数接受相同接口类型的多个参数
我想使用 StructureMap ObjectFactory 来处理 WCF 服务使用的类的实例化。虽然我有限的经验足以处理一个接口和实现该接口的单个类之间的简单 1:1 映射,但我遇到了一个障碍,即构造函数接受同一接口的多个参数。
我认为我可以通过给每个映射一个名称来将多个具体类关联到同一个接口,但是如何告诉 StructureMap 第一个和第二个构造函数参数使用什么映射?
这是我希望 ObjectFactory 为我处理的类:
public class MasterPolicy {
public MasterPolicy(IPolicy alfaPolicy, IPolicy numericPolicy)
{
AlphaPolicy = alphaPolicy;
NumericPolicy = numericPolicy;
}
public IPolicy AlphaPolicy {get; private set; }
public IPolicy NumericPolicy {get; private set; }
public bool IsValid(string s)
{
if (!AlphaPolicy.IsValid(s)) return false;
if (!NumericPolicy.IsValid(s)) return false;
return true;
}
}
IPolicy 接口由多个类实现:(
public interface IPolicy
{
bool IsValid(string s);
}
public class AlphaPolicy : IPolicy
{
public bool IsValid(string s) { return true; }
}
public class NumericPolicy : IPolicy
{
public bool IsValid(string s) { return true; }
}
当然,MasterPolicy 也可以实现 IPolicy 接口)。
I want to use StructureMap ObjectFactory to handle the instantiation of my classes used by my WCF service. While my limited experience is sufficient to handle the simple 1:1 mappings between one interface and that one, single class that implements it, I've hit a snag where a constructor accepts multiple parameters of the same interface.
I reckon I can associate multiple concrete classes to the same interface by giving each mapping a name, but how do I tell StructureMap what mapping to use for the first and the second constructor parameter?
This is the class I want ObjectFactory to handle for me:
public class MasterPolicy {
public MasterPolicy(IPolicy alfaPolicy, IPolicy numericPolicy)
{
AlphaPolicy = alphaPolicy;
NumericPolicy = numericPolicy;
}
public IPolicy AlphaPolicy {get; private set; }
public IPolicy NumericPolicy {get; private set; }
public bool IsValid(string s)
{
if (!AlphaPolicy.IsValid(s)) return false;
if (!NumericPolicy.IsValid(s)) return false;
return true;
}
}
The IPolicy interface is implemented by more than one class:
public interface IPolicy
{
bool IsValid(string s);
}
public class AlphaPolicy : IPolicy
{
public bool IsValid(string s) { return true; }
}
public class NumericPolicy : IPolicy
{
public bool IsValid(string s) { return true; }
}
(Of course, MasterPolicy could too implement the IPolicy interface).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以指定构造函数依赖项并告诉结构映射哪个命名参数应该具有哪个依赖项:
You can specify constructor dependencies and tell structure map which named argument should have which dependency: