2
interface IRecipe<T>
{
    ICollection<IIngredient<T>> Ingredients { get; set; }
    T Cook();
}

interface IIngredient<T> {}

public class Cheese : IIngredient<Pizza> {}
public class Tomato : IIngredient<Pizza> {}

public class Egg    : IIngredient<Omlette> {}

我希望当我请求一个IRecipe<SomeType>StructureMap 实例时,可以找到所有实现并以某种方式IIngredient<SomeType>注册它们。Recipe

因此,例如,如果我请求接口IRecipe<Pizza>,我将获得Recipe<Pizza>具有正确成分的具体实例。

有什么办法可以做到这一点?

4

1 回答 1

4

是的,这可以通过 StructureMap 完成。

我已经只读了,添加了 and的ICollection<IIngredient<T>> Ingredients具体实现,PizzaOmlette扩展了CheeseandTomato可用于两者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));
}
于 2013-06-18T08:53:06.633 回答