1

I search about base controller in asp.net mvc 6 however there is no any source (as far as i check).So how can i add base controller in asp.net mvc and use services on constuctor method or create new methods in base controller or any idea in order to use anything like base controller?

Any help will be appreciated.

Thanks.

2 Answers 2

3

You can add base controller in the following way:

public class BaseController : Controller
{
    public IService Service { get; }

    public BaseController(IService service)
    {
        Service = service;
    }
}

Then, you can create your own controller and inherit BaseController instead of Controller class.

public class NewController : BaseController
{
    public NewController(IService service) : base(service)
    {             
    }

    public IActionResult NewAction()
    {
        var result = Service.ServiceMethod();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You need a constructor in NewController which accept IService parameter and pass it to base(service)
Hi Dmitry may you please send your answer and show constuctor method because i tried @Ognjen Babic's answer however cannt pass parameter to base service thanks
0

With Microsoft.Extensions.DependencyInjection name space gives us access to the following extension method HttpContext.RequestServices.GetService

Here’s the source code of our BaseController class

public abstract class BaseController<T> : Controller where T : BaseController<T>
{
    private IService service;
    protected IService _service => telemetryInitializer ?? (telemetryInitializer = HttpContext.RequestServices.GetService<West.TelemetryService.ITelemetryHelper>());
}

The OrderController class extends this abstract BaseController

public class OrderController : BaseController<OrderController>
{
    private readonly IOrderManager _orderManager;
    public OrderController(IOrderManager orderManager)
    {
        _orderManager = orderManager;
    }
    [HttpGet]
    public string Get()
    {
        Logger.LogInformation("Hello World!");
        return "Inside the Get method of OrderController";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.