我的一个班级有两个构造函数:
public class Foo
{
public Foo() { }
public Foo(string bar) { }
}
当我从统一解决这个问题时,我得到一个异常,因为它会查找string bar
参数。但是我希望Unity使用没有参数的构造函数来实例化这个类。我怎样才能做到这一点?
我使用LoadConfiguration
方法从配置文件中注册类型。
Unity容器配置:
container.LoadConfiguration("containerName");
配置文件:
<unity xmlns="">
<typeAliases>
<typeAlias alias="string" type="System.String, mscorlib" />
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
</typeAliases>
<containers>
<container name="containerName">
<types>
<type type="IFoo, Assembly"
mapTo="Foo, Assembly" />
...
</types>
</container>
</containers>
</unity>
答案 0 :(得分:3)
SELECT u_data.lane_id AS LaneId,
origin_city.pcode AS origin_pcode,
dest_city.pcode AS dest_pcode
FROM customer_routes AS CustomerRoute
INNER JOIN countries AS origin_country ON ( origin_country.id = CustomerRoute.origin_country )
INNER JOIN countries AS dest_country ON ( dest_country.id = CustomerRoute.dest_country )
INNER JOIN states AS origin_state ON ( origin_state.id = CustomerRoute.origin_state )
INNER JOIN states AS dest_state ON ( dest_state.id = CustomerRoute.dest_state )
INNER JOIN postalcodes AS origin_city ON ( origin_city.id = CustomerRoute.origin_city )
INNER JOIN postalcodes AS dest_city ON ( dest_city.id = CustomerRoute.dest_city )
INNER JOIN portfolios AS p ON ( p.id = CustomerRoute.portfolio_id )
LEFT JOIN supplier_uquotes_data AS u_data ON ( CustomerRoute.id = u_data.lane_id AND u_data.mode = '".$mode."')
WHERE CustomerRoute.portfolio_id = '".$_SESSION["portfolioid"]."' AND u_data.supplier_id
IN (".implode(',',$_SESSION['supplierid']).") GROUP BY CustomerRoute.id
属性指定在解析服务时应使用哪个构造函数
[InjectionConstructor]
这种方法使你的类与Unity相结合,你的类变得不那么可重复了(想象你需要在需要使用另一个构造函数的不同场景中使用public class Foo : IFoo
{
[InjectionConstructor]
public Foo() { }
public Foo(string bar) { }
}
)这样不推荐,请阅读有关this here
更好的方法是使用API并按如下方式注册您的课程
Foo
在这里,您明确定义了如何解析依赖关系。
或者您可以使用container.RegisterType<IFoo>(new Foo());
配置文件,即在Xml
元素中指定<contructor>
元素
请注意,我们未在<register>
元素中指定<params>
子元素
如果没有
<constructor>
个子元素,则表示应该调用零参数构造函数
详细了解<param>
架构here