gpt4 book ai didi

dependency-injection - 温莎城堡传递构造函数参数

转载 作者:行者123 更新时间:2023-12-03 14:46:15 24 4
gpt4 key购买 nike

我有一个带有一些属性的 IAddress 类。然后我有一个实现这个接口(interface)的具体类型。这种具体类型有几个我可以使用的不同构造函数。如何在运行时将参数值传递给这些构造函数之一?我不能使用配置文件,因为我将多次重用这个具体类型,并且每次参数值都会不同。

IWindsorContainer container = new WindsorContainer(new XmlInterpreter());
IAddress address = container.Resolve<IAddress>();


public interface IAddress
{
string Address1 { get; set; }
string Address2 { get; set; }
string City { get; set; }
string State { get; set; }
string ZipCode { get; set; }
}


class TestAddress : IAddress
{

private string _address1;
private string _address2;
private string _city;
private string _countyName;
private string _state;
private string _zipCode;

public string Address1
{
get { return _address1; }
set { _address1 = value; }
}

public string Address2
{
get { return _address2; }
set { _address2 = value; }
}

public string City
{
get { return _city; }
set { _city = value; }
}

public string State
{
get { return _state; }
set { _state = value; }
}

public string ZipCode
{
get { return _zipCode; }
set { _zipCode = value; }
}

public string CountyName
{
get { return _countyName; }
set { _countyName = value; }
}


public MelissaAddress(string address1, string address2, string city, string state, string zipcode)
{
Address1 = address1;
Address2 = address2;
City = city;
State = state;
ZipCode = zipcode;
}

public MelissaAddress(string address1, string address2, string zipcode) : this(address1, address2, null, null, zipcode)
{ }

public MelissaAddress(string address1, string address2, string city, string state) : this(address1, address2, city, state, null)
{ }
}

最佳答案

您可以使用 Resolve(object argumentsAsAnonymousType)Resolve(IDictionary arguments) . Windsor 将选择最匹配的构造函数。

例如,这将选择您的第二个构造函数:

container.Resolve<IAddress>(
new {address1 = "myaddress1", address2 = "myaddress2", zipcode = "myzipcode"}
)

关于dependency-injection - 温莎城堡传递构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/784253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com