2012-07-29 68 views
2

我使用this document来使用类型化工厂并将参数传递给构造函数。 当我尝试传递代码中显示的2个参数(1,“fo”)时,键入的工厂给了我这个错误。将参数传递给Castle Windsor Typed Factory

enter image description here

public class SomeClass { 
    public ITypedFactory2 F2 { get; set; } 
    public void SomeFunction() { 
     var req = F2.Create<IGetFooRequest>(1, "fo"); // ERROR HERE 
    } 
} 
public class GetFooRequest : IGetFooRequest { 
    public int Bar { get; private set; } 
    public string Ton { get; private set; } 
    public GetFooRequest(int bar, string ton) { 
     Bar = bar; 
     Ton = ton; 
    } 
} 
public interface IGetFooRequest{ 
    int Bar { get; } 
    string Ton { get; } 
}  
public interface ITypedFactory2 { 
    T Create<T>(int param1, string param2); 
    void Release(object t); 
} 

,这是温莎安装部分...

container.AddFacility<TypedFactoryFacility>(); 
container.Register(Component.For<ITypedFactory2>().AsFactory()); 
container.Register(AllTypes 
      .FromAssemblyContaining<IGetFooRequest>() 
      .Where(type => type.Name.EndsWith("Request")) 
      .WithService.AllInterfaces().LifestyleTransient()); 

为什么说解决不了非可选依赖...?我通过了(1,“fo”);我真的不明白为什么会发生这种情况......请帮忙。

回答

7

我有同样的问题,只是想出了答案。工厂方法的参数名称和类构造函数的名称必须匹配,不区分大小写。

因此改变你的工厂接口

public interface ITypedFactory2 { 
    T Create<T>(int **bar**, string **ton**); 
    void Release(object t); 
} 

或者你的类

public class GetFooRequest : IGetFooRequest { 
    public int Bar { get; private set; } 
    public string Ton { get; private set; } 
    public GetFooRequest(int **param1**, string **param2**) { 
     Bar = bar; 
     Ton = ton; 
    } 
} 
+0

这不是标记为答案? – neverseenjack 2017-03-30 15:49:33

+0

它被标记为答案 – 2018-01-19 02:00:23

2

我看着我自己的代码,并说,(int param1,string param2)看起来不太好。让我使用(int bar,string ton)...并且命名解决了问题。 LoL难以置信,我没有看到那份文件提到了命名的重要性。

幸运的是,我记得intro here说依赖关系首先按名称解析,然后按类型解决。所以这是按名称部分做的工作,而按类型部分则进入了水中。无论如何,我很高兴我想出了如何使用它,所以我在这里与任何需要它的人分享我的答案。

+0

这种反应基本上是重复以前的答案。 Wabble提供的答复应该在这里标记为答案。 – neverseenjack 2017-03-30 15:53:17

+0

@neverseenjack看看日期,因为我在Wabble看了这一年之前回答了我自己的问题。 Anway,我把他的帖子标记为答案。 – Tom 2017-04-14 00:47:51