C# Interface Method calls from a controller

Posted by ArjaaAine on Stack Overflow See other posts from Stack Overflow or by ArjaaAine
Published on 2014-05-29T21:22:27Z Indexed on 2014/05/29 21:25 UTC
Read the original article Hit count: 208

I was just working on some application architecture and this may sound like a stupid question but please explain to me how the following works:

Interface:

public interface IMatterDAL
{
    IEnumerable<Matter> GetMattersByCode(string input);
    IEnumerable<Matter> GetMattersBySearch(string input);
}

Class:

 public class MatterDAL : IMatterDAL
{
    private readonly Database _db;

    public MatterDAL(Database db)
    {
        _db = db;
        LoadAll(); //Private Method
    }

    public virtual IEnumerable<Matter> GetMattersBySearch(string input)
    {
        //CODE
        return result;
    }

    public virtual IEnumerable<Matter> GetMattersByCode(string input)
    {
       //CODE
        return results;
    }

Controller:

public class MatterController : ApiController
{
    private readonly IMatterDAL _publishedData;

    public MatterController(IMatterDAL publishedData)
    {
        _publishedData = publishedData;
    }

    [ValidateInput(false)]
    public JsonResult SearchByCode(string id)
    {
        var searchText = id; //better name for this
        var results = _publishedData.GetMattersBySearch(searchText).Select(
            matter =>
            new
                {
                    MatterCode = matter.Code,
                    MatterName = matter.Name, 
                    matter.ClientCode, 
                    matter.ClientName
                });
        return Json(results);
    }

This works, when I call my controller method from jquery and step into it, the call to the _publishedData method, goes into the class MatterDAL.

I want to know how does my controller know to go to the MatterDAL implementation of the Interface IMatterDAL. What if I have another class called MatterDAL2 which is based on the interface. How will my controller know then to call the right method?

I am sorry if this is a stupid question, this is baffling me.

© Stack Overflow or respective owner

Related posts about c#

Related posts about class