Search code examples
asp.netinterfacen-tier-architecture3-tierbll

the bll,dal and interfaces implementation


My question is related to the bll,dal,interfaces.

My project's constructure more or less like this. BLL, DAL, OBJ and 3 layer architecture (As I dont repeat question and codes again,I give the link here)

My question is why should I use interfaces,what is the benefits.and how can apply interfaces based on the project structure which is gaved above. could u provide link or answers.thank you all


Solution

  • Interfaces allow you to define the behavior without the actual implementation, think of it as a contract.

    If you only have one implementation, then an interface is not very useful and is not recommended.

    Where interfaces shine, is when you have multiple implementations of the same logic. Say for example the data access layer (DAL), like this:

    public interface IPersonRepository
    {
        Person CreatePerson(string firstName, string lastName, int age);
        Person LoadPerson(int personId);
        Person SavePerson(string firstName, string lastName, int age);
        bool DeletePreson(int personId);
    }
    

    Now if you have a SQL Server database, then you could have a repository class that implements the IPersonRepository interface, like this:

    public class SqlServerPersonRepository : IPersonRepository
    {
        // Implement SQL Server specific logic here
    }
    

    Let's say you want to support Oracle, as well, then you create an OraclePersonRepository, like this:

    public class OraclePersonRepository : IPersonRepository
    {
        // Implement Oracle specific logic here
    }
    

    What is also useful is that you can create a mock person repository (for testing), like this:

    public class MockPersonRepository : IPersonRepository
    {
        // Implement mock logic here
    }