假设我的几个控制器构造函数采用接口 - IPetInterface IPetInterface有3个具体实现。
如何配置StructureMap以根据需要的控制器提供其中一个具体实现。
粗略的例子......
class DogStuff: IPetInterface{}
class CatStuff: IPetInterface{}
class GiraffeStuff: IPetInterface{}
class DogController : Controller
{
DogController(IPetInterface petStuff)
// some other stuff that is very unique to dogs
}
class CatController : Controller
{
CatController(IPetInterface petStuff)
// some other stuff that is very unquie to cats
}
答案 0 :(得分:5)
使用问题中提供的类和接口,此注册将执行:
For<DogController>().Use<DogController>()
.Ctor<IPetInterface>("petStuff").Is<DogStuff>();
For<CatController>().Use<CatController>()
.Ctor<IPetInterface>("petStuff").Is<CatStuff>();
For<GiraffeController>().Use<GiraffeController>()
.Ctor<IPetInterface>("petStuff").Is<GiraffeStuff>();
如果使用相同的模式增加超过3个注册,我会考虑使用基于约定的注册,而不是基于命名自动为每个控制器注册相应的“东西”。这可以实现using an IRegistrationConvention。
答案 1 :(得分:2)
试试这个:
class Stuff<T> : IPetInterface<T> where T : IPet { ... }
interface IPetInterface<T> where T : IPet { ... }
abstract class PetController<T> : Controller where T : IPet
{
protected PetController<T>(IPetInterface<T> stuff)
{ ... }
}
class CatController : PetController<Cat>
{
public CatController(IPetInterface<Cat> stuff) : base(stuff) {}
...
}
class DogController : PetController<Dog> { ... }