【问题标题】:MVC3 & StructureMap, injecting concrete class based on the controllerMVC3 & StructureMap,基于控制器注入具体类
【发布时间】:2011-04-28 13:53:51
【问题描述】:

假设我的几个控制器构造函数采用接口 - IPeInterface 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
}

【问题讨论】:

  • 虽然我确信它可以使用 StructureMap 完成(我自己更喜欢 Unity,所以我不确定如何使用 StructureMap 来完成)你确定你的设计是正确的?根据您的描述,界面可能通用....
  • @BFree:可能太笼统了。目前我对每个“宠物”都有单独的接口,但它们是相同的,所以我想知道这是否可能/值得

标签: c# asp.net-mvc-3 structuremap


【解决方案1】:

使用问题中提供的类和接口,此注册可以:

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

【讨论】:

  • 谢谢,正是我想要的那种信息!
【解决方案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> { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多