Reputation: 100288
I have implemented (using System.Configuration
namespace) and configured next App.config
structure:
<bot>
<strategies>
<add name="TestStrategy" type="Bot.Strategy.Test" >
<indicators>
<add name="Foo" type="Bot.Indicators.Foo, Bot" />
<add name="Bar" type="Bot.Indicators.Bar, Bot" />
</indicators>
<orders>
<add id="123" amount="0.1" />
</orders>
</add>
</strategies>
</bot>
for next classes:
class TestStrategy : IStrategy
{
public TestStrategy(IEnumerable<IIndicator> indicators, IEnumerable<Order> orders) { }
}
interface IIndicator { }
class Order
{
public int ID { get; set; }
public double Amount { get; set; }
}
So how can I read my App.config to instantiate IEnumerable<IStrategy>
calling the constructor of each with appropriate IEnumerable<IIndicator>
and IEnumerable<Order>
using LINQ?
I have already next:
var section = ((BotSection)ConfigurationManager.GetSection("bot"));
return from strategy in section.Strategies
let strategyType = Type.GetType(strategy.Type)
where !strategyType.IsInterface && !strategyType.IsAbstract && typeof(IStrategy).IsAssignableFrom(strategyType)
select (IStrategy)Activator.CreateInstance(strategyType, ?);
Upvotes: 0
Views: 1699
Reputation: 172676
If your BotSection
is defined correctly, you can do this (note the sub queries):
return
from strategy in section.Strategies
let strategyType = Type.GetType(strategy.Type)
where !strategyType.IsInterface && !strategyType.IsAbstract
&& typeof(IStrategy).IsAssignableFrom(strategyType)
let indicators = (
from indicator in strategy.Indicators
let indicatorType = Type.GetType(indicator.Type)
select (IIndicator)Activator.CreateInstance(indicatorType))
let orders = (
from order in strategy.Orders
let id = order.Id
select new Order { Id = order.Id, Amount = order.Amount })
select (IStrategy)Activator.CreateInstance(strategyType, indicators, orders);
Upvotes: 1