MVC3和StructureMap,基于控制器注入具体类

Dve*_*Dve 1 c# structuremap asp.net-mvc-3

假设我的几个控制器构造函数采用接口 - 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
}
Run Code Online (Sandbox Code Playgroud)

PHe*_*erg 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>();
Run Code Online (Sandbox Code Playgroud)

如果使用相同的模式增加超过3个注册,我将使用基于约定的注册来调查,而不是基于命名自动为每个控制器注册相应的"东西".这可以使用IRegistrationConvention来实现.