我想在不传递任何“内核”容器的情况下使用基于工厂的依赖注入,这样就无法实例化一个类,而不必从“顶部”明确传递它的依赖关系。构造函数的自动工厂生成器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 –