views:

151

answers:

1

I see tons of material on how to inject services using the ControllerBuilder.Current.SetControllerFactory but what if I wanted to resolve my services in the model? Would I have to get them from the Controller layer and pass them up?

+1  A: 

Ideally you should not be injecting services into the model as this would require you to register your model with the container.

If you need to use a service within a model instance, pass the service in as a method argument and then you can inject the service into the controller.

Without knowing more about the scenario it is hard to give clearer advice, however the following outline may help:

public interface IService
{
  // ... describe the contract the service must fulfill
}

public class Model
{
  public void DoSomething( IService service )
  {
    // ... do the necessary work using the service ...
  }
}

public class AController : Controller
{
  private readonly IService _injectedService;

  public AController( IService injectedService )
  {
    _injectedService = injectedService;
  }
  public ActionResult SomeAction( int modelId )
  {
    // ... get the model from persistent store
    model.DoSomething( _injectedService );
    // ... return a view etc
  }
}
Neal