使用依赖注入初始化抽象类对象

时间:2017-07-14 03:58:27

标签: c# dependency-injection abstract-class

我继承了ApiController,下面是我重写的ExecuteAsync方法,带有依赖注入,

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

这是我的服务界面

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

这是班级,

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

当我执行此方法时,BaseController类中的person对象仍为null。在抽象类中初始化对象应该更改什么?

1 个答案:

答案 0 :(得分:0)

请检查此帖子,看看这是否能回答您的问题 - Registering implementations of base class with Autofac to pass in via IEnumerable

您必须适当地注册抽象类的子类。