我通过autofac创建(实例化)一个分层类结构:
order
|
--------> customerPersonDatails
| |
| ----------------->name
| |
| ------------------>surname
|--------> customerBillingDetail
| |
| ----------------->currency
| |
| ------------------>bank
|
|
--------->
我想要做的是“递归地”创建订单对象并填充其属性
var builder = new ContainerBuilder();
//register components
builder.RegisterType<order>().PropertiesAutowired().OnActivated(order_Init); //<-- onactivated method will be used to populate properties
builder.RegisterType<customerPersonDatails>().PropertiesAutowired();
builder.RegisterType<customerBillingDetail>().PropertiesAutowired();
public static Action<IActivatedEventArgs<order>> order_Init = (c) =>
{
c.Instance.customerPersonDatails.name = //<-- how to pass the current value provided from the foreach
c.Instance.customerPersonDatails.surname =
c.Instance.customerBillingDetail.currency =
c.Instance.customerBillingDetail.bank =
};
//iteration through my orders and create recursively the object
foreach(string currentOrder in Orders)
{
using (var scope = Container.BeginLifetimeScope())
{
//each time "resolve" is called i get a new istance of the order object with all its properties instatiated and the OnActivated method is correctly fired
//how can i pass into that method the currentOrder values in order to complete/populate the order structure with my values (currentOrder.name, currentOrder.surname, ... )
var ord = scope.Resolve<order>();
//here i have to pass currentOrder's value in some way into "order_Init"(how to do it?)
//do others stuff
ord.serialize();
}
}
问题是:如何将当前值(currentOrder.name等)传递给函数order_Init 我注意到函数“order_Init”的“c”参数有一些属性,如参数/上下文/组件....我可以使用其中一个吗?如何?
答案 0 :(得分:1)
为了实现这种可能性,您应该重新设计您的解决方案并创建一些由Autofac Delegate Factories支持的工厂方法或工厂代表
答案 1 :(得分:1)
以下是完整的工作示例,可帮助您修改解决方案
public void Test()
{
var builder = new ContainerBuilder();
builder.RegisterType<order>().PropertiesAutowired();
//builder.RegisterType<customerPersonDatails>().PropertiesAutowired();
//builder.RegisterType<customerBillingDetail>().PropertiesAutowired();
var container = builder.Build();
var Orders = new[] { "test" };
foreach (string currentOrder in Orders)
{
using (var scope = container.BeginLifetimeScope())
{
var ordFactory = scope.Resolve<order.Factory>(); //<------changed from "Resolve<order>" to "Resolve<order.Factory>"
var ord = ordFactory.Invoke(currentOrder); //<------ added in order to pass the data
}
}
}
public class order
{
//added delegate
public delegate order Factory(string currentOrder);
//added constructor
public order(string currentOrder)
{
//use the constructor parameter to populate the class property, is it correct?
this.orderCode = currentOrder;
Debug.WriteLine("I am in order constructor with currentOrder = " + currentOrder);
}
public string orderCode { get; set; }
调试输出符合预期
I am in order constructor with currentOrder = test