Skip to main content
 首页 » 编程设计

c#之MVC3 & StructureMap,基于 Controller 注入(inject)具体类

2024年01月25日30zhwl

假设我的几个 Controller 构造函数采用接口(interface) - IPetInterface IPetInterface 有 3 个具体实现。

您将如何配置 StructureMap 以根据需要它的 Controller 提供具体实现之一。

粗略的例子....

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 
} 

请您参考如下方法:

使用问题中提供的类和接口(interface),此注册将执行:

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 个具有相同模式的注册,我会考虑使用基于约定的注册,而不是根据命名自动为每个 Controller 注册相应的“内容”。这可以实现using an IRegistrationConvention .