简体   繁体   中英

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM