我想在不傳遞任何「內核」容器的情況下使用基於工廠的依賴注入,這樣就無法實例化一個類,而不必從「頂部」明確傳遞它的依賴關係。構造函數的自動工廠生成器DI
手動方式,這樣做需要在引導這樣的代碼:
static void Main(string[] args)
{
// simplified example, can require classes in reality
ABFactory abFactory = (data1) => new AB(data1);
ACAFactory acaFactory = (data1) => new ACA(data1);
ACFactory acFactory = (x) => new AC(x, acaFactory);
IA a = new A(1, new AA(1, new AAA(), new AAB()), abFactory, acFactory);
a.Action(123);
}
當工廠是指
delegate IAB ABFactory(string data1);
delegate IAC ACFactory(int x);
delegate IACA ACAFactory(int data1);
有什麼我可以使用,使工廠建設更容易,甚至自動?有不同的工廠類型支持(池,ThreadLocal緩存等)?
UPDATE
一些實際的代碼示例:
public interface IItemSetSpawnController
{
void TransitSpawned();
}
public class ItemSetSpawnController : IItemSetSpawnController
{
readonly GameMap.ItemSet _set;
readonly LootableFactoryDelegate _lootableFactory;
readonly IFiber _fiber;
readonly int _defaultRespawnTime;
public ItemSetSpawnController([NotNull] GameMap.ItemSet set, int defaultRespawnTime, [NotNull] LootableFactoryDelegate lootableFactory, IFiber fiber)
{
if (set == null) throw new ArgumentNullException(nameof(set));
if (lootableFactory == null) throw new ArgumentNullException(nameof(lootableFactory));
if (set.Items.Count == 0) throw new ArgumentException("Empty set", nameof(set));
_set = set;
_lootableFactory = lootableFactory;
_fiber = fiber;
_defaultRespawnTime = defaultRespawnTime;
}
public void TransitSpawned()
{
// Fiber.Schedule for respawning
}
}
public delegate IItemSetSpawnController ItemSetSpawnControllerFactory(
[NotNull] GameMap.ItemSet set, int defaultRespawnTime, [NotNull] LootableFactoryDelegate lootableFactory, IFiber fiber);
protected virtual void AddMapLootables()
{
foreach (var set in ItemSets)
{
if (set.Items.Count == 0) continue;
var c = ItemSetSpawnControllerFactory(
set,
Settings.LootRespawnTime,
LootableFactory,
ExecutionFiber);
c.TransitSpawned();
}
}
Autofac內置這個概念:http://docs.autofac.org/en/latest/advanced/delegate-factories.html –