开发者

MVC3 & StructureMap, injecting concrete class based on the controller

Say several of my controllers constructors take an interface - IPetInterface There are 3 concrete implementations of IPetInterface.

How would you configure StructureMap to supply one of the concrete implementations based on the controller that needs it.

crude example ....

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
}
开发者_Go百科


With the classes and interfaces provided in the question, this registration would do:

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>();

If this grows beyond 3 registrations with the same pattern I would look into using a convention based registration instead that would automatically register a corresponding "stuff" for each controller based on the naming. This could be achieved using an IRegistrationConvention.


Try this:

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> { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜