【发布时间】:2015-09-03 08:23:04
【问题描述】:
我想在不传递任何“内核”容器的情况下使用基于工厂的依赖注入,因此如果没有从“顶部”显式传递其依赖项,就不可能实例化一个类。
执行此操作的手动方式需要在引导程序中使用如下代码:
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 缓存等)?
更新
一些真实的代码示例:
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 内置了这个概念:docs.autofac.org/en/latest/advanced/delegate-factories.html
标签: c# dependency-injection factory factory-pattern reflection.emit