假设以下类结构:
ClassA (IClassB classb, IClassC classc) : IClassA
ClassB (IClassC classc) : IClassB
ClassC1 () : IClassC
ClassC2 () : IClassC
假设我使用ClassC1
时,只要使用IClassA
专门解析container.GetInstance<IClassA>()
,即new ClassA(
new ClassB (new ClassC1()),
new ClassC1()
)
将返回
For<ClassA>().Nest(x => x.For<IClassC>().Use<ClassC1>())
我可以在StructureMap中做这样的事情吗? (理想情况下,类似于package Learning;
public class MatchScore {
private String MatchNumber;
private String KillsInMatch;
private String DeathsInMatch;
public void setMatchNumber(String nameIn){
MatchNumber = nameIn;
}
public String getName(){
return MatchNumber ;
}
public void setKillsInMatch(String killsIn){
KillsInMatch = killsIn;
}
public String getKillsInMatch(){
return KillsInMatch;
}
public void setDeathsInMatch(String deathsIn){
DeathsInMatch = deathsIn;
}
public String getDeathsinMatch(){
return DeathsInMatch;
}
public void totalStatus(double Stats){
System.out.printf("This game is %s ", MatchNumber);
System.out.printf("you killed-this many %s", KillsInMatch);
System.out.printf("but you died-this many time %s", DeathsInMatch);
}
}
,但任何事情都可以。)
答案 0 :(得分:1)
这就是我得到的:
public interface IClassA
{
}
public interface IClassB
{
}
public interface IClassC
{
}
public class ClassA: IClassA
{
public ClassA(IClassB classb, IClassC classc)
{
Console.WriteLine("ClassA");
Console.WriteLine(" ClassB: {0}", classb.GetType());
Console.WriteLine(" ClassC: {0}", classc.GetType());
}
}
public class ClassB : IClassB
{
public ClassB(IClassC classc)
{
Console.WriteLine("ClassB");
Console.WriteLine(" ClassC: {0}", classc.GetType());
}
}
public class ClassC1 : IClassC
{
public ClassC1()
{
Console.WriteLine("ClassC1");
}
}
public class ClassC2 : IClassC
{
public ClassC2()
{
Console.WriteLine("ClassC2");
}
}
class Program
{
static void Main(string[] args)
{
IContainer container = ConfigureDependencies();
container.GetInstance<IClassA>();
container.GetInstance<IClassB>();
}
private static IContainer ConfigureDependencies()
{
return new Container(x =>
{
x.For<IClassA>().Use<ClassA>();
x.For<IClassB>().Use<ClassB>();
x.For<IClassC>().Use(z => z.RootType == typeof(ClassA) ? (IClassC) z.GetInstance<ClassC1>() : z.GetInstance<ClassC2>());
});
}
}
IClassC
的具体类型由RootType
确定。
这是输出:
ClassC1
ClassB
ClassC: MongodbEnumerable.ClassC1
ClassA
ClassB: MongodbEnumerable.ClassB
ClassC: MongodbEnumerable.ClassC1
ClassC2
ClassB
ClassC: MongodbEnumerable.ClassC2
它显示ClassC1
用于构建ClassA
及其依赖项,但用于构建单独的IClassB
ClassC2
。