예이 작업은 StructureMap에서 수행 할 수 있습니다.
내가 읽기 전용 ICollection<IIngredient<T>> Ingredients
을했습니다, 여기에 등록
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;
}
방법이다 Pizza
및 Omlette
의 구체적인 구현을 추가하고 모두 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> { }
사용할 수 Cheese
및 Tomato
확장 그리고 두 가지 테스트 방법
[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));
}
화려한 감사합니다. 'ConnectImplementationsToTypesClosing'과'AddAllTypesOf' 사이의 차이점을 아십니까? 그들은 둘 다 여기에서 같은 결과를 얻는 것으로 보입니다. – fearofawhackplanet
'AddAllTypesOf'를 사용하면 'IIngredient'에 대한 두 번째 테스트가 하나의 성분 만 반환되어 '치즈'와 '토마토'(즉, 'IIngredient ')의 'IIngredient '의 첫 번째 정의가 등록되었습니다. 대신 ConnectImplementationsToTypesClosing을 사용하여 두 번째 테스트를 수정했습니다. –
qujck