是的,这可以通过 StructureMap 完成。
我已经只读了,添加了 and的ICollection<IIngredient<T>> Ingredients
具体实现,Pizza
并Omlette
扩展了Cheese
andTomato
可用于两者Recipe
public class Pizza { }
public class Omlette { }
public class Recipe<T> : IRecipe<T> where T : class, new()
{
private readonly IEnumerable<IIngredient<T>> _ingredients;
public Recipe(IEnumerable<IIngredient<T>> ingredients)
{
_ingredients = ingredients;
}
public ICollection<IIngredient<T>> Ingredients
{
get { return _ingredients.ToList(); }
}
public T Cook()
{
return new T();
}
}
public interface IRecipe<T>
{
ICollection<IIngredient<T>> Ingredients { get; }
T Cook();
}
public interface IIngredient<T> { }
public class Cheese : IIngredient<Pizza>, IIngredient<Omlette> { }
public class Tomato : IIngredient<Pizza>, IIngredient<Omlette> { }
public class Egg : IIngredient<Omlette> { }
下面是注册方法
public StructureMap.IContainer ConfigureStructureMap()
{
StructureMap.IContainer structureMap;
StructureMap.Configuration.DSL.Registry registry =
new StructureMap.Configuration.DSL.Registry();
registry.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.ConnectImplementationsToTypesClosing(typeof(IIngredient<>));
});
structureMap = new StructureMap.Container(registry);
structureMap.Configure(cfg =>
cfg.For(typeof(IRecipe<>)).Use(typeof(Recipe<>)));
return structureMap;
}
和两种测试方法
[Test]
public void StructureMapGetInstance_Pizza_ReturnsTwoIngredients()
{
StructureMap.IContainer structureMap = ConfigureStructureMap();
var pizza = structureMap.GetInstance<IRecipe<Pizza>>();
Assert.That(pizza.Ingredients.Count, Is.EqualTo(2));
}
[Test]
public void StructureMapGetInstance_Omlette_ReturnsThreeIngredients()
{
StructureMap.IContainer structureMap = ConfigureStructureMap();
var omlette = structureMap.GetInstance<IRecipe<Omlette>>();
Assert.That(omlette.Ingredients.Count, Is.EqualTo(3));
}