-1

I am inheriting ApiController and below is my overridden ExecuteAsync method with dependency injection,

public abstract class BaseController : ApiController
{
    private IMyService _myService;
    public PersonModel person;
    protected BaseController(IMyService myService)
    {
        _myService = myService;
    }

    public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
    {
        _myService.Initialize(person);
    }
}

This is my service interface,

public interface IMyService 
{
    HttpResponseMessage Initialize(PersonModel person);
}

Here is the class,

public class MyService : IMyService
{
    public HttpResponseMessage Initialize(PersonModel person)
    {
        //Initializing person model from db
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

When I execute this method, person object in the BaseController class is still null. What should I change to initialize the object in abstract class?

dev999
  • 1
  • 1
  • 2
    I'm guessing you're doing something along the lines of `person = new PersonModel()` inside `Initialize`. That won't work at all. You'll need it to *return* a person model, or (an ugly workaround), use `ref`. – Rob Jul 14 '17 at 04:07
  • Which dependency framework are you using? – ArunGeorge Jul 14 '17 at 04:12
  • @ArunGeorge Autofac – dev999 Jul 14 '17 at 04:16
  • You initialize an application component (`IMyService`) with runtime data (`PersonModel`). [This is anti-pattern](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99). – Steven Jul 14 '17 at 07:04
  • Simply put, [*never* use a base class in MVC or WebApi when using DI](https://stackoverflow.com/a/6119341/181087). This can be solved in a DI-friendly way by using a [global filter](https://stackoverflow.com/a/9521363) to initialize your data. – NightOwl888 Jul 14 '17 at 19:00

1 Answers1

-1

Please check this thread to see if this answers your question - Registering implementations of base class with Autofac to pass in via IEnumerable

You will have to register the child classes of your abstract class appropriately.

ArunGeorge
  • 495
  • 5
  • 11