简体   繁体   中英

Why set up a constructor in a class to set a base parameter when I could do the same in a class it inherits from?

I have the following code:

public abstract class ApiBaseController : ApiController
{
    protected IUow Uow { get; set; }
}

and:

public class ContentStatusController : ApiBaseController
{

    public ContentStatusController(IUow uow)
    {
        Uow = uow;
    }
}

Is there any reason why I could not code the assignment of Uow (using IOC) in the ApiBaseController?

The reason I ask is because I am trying to do something similar to the Code Camper application sample and I notice that in that sample the Unit of work is assignment is always performed in the constuctors of the controllers themselves rather than in the ApiBaseConstructor. In the examples I see this is the only thing that's done in the constructors.

If I did the assignement in the base controller then how could I code that and would Uow still need to have "protected" for it to be available in controllers that inherit from the ApiBaseController?

Your IOC container is injecting dependencies via constructors. If you want to continue to use that mechanism (some containers allow eg property injection, but not everyone likes to do that) then you'll still need to have the same constructor in your derived class to pass the injected component down to the base class 1 .

Something like:

public abstract class ApiBaseController : ApiController
{
    public ApiBaseController(IUow uow)
    {
        Uow = uow;
    }
    protected IUow Uow { get; private set; }
}
public class ContentStatusController : ApiBaseController
{
    public ContentStatusController(IUow uow) : base(uow) //<-- This is needed
    {
    }
}

1 Because classes don't inherit constructors.

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