Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. Why should I use Interface type of object in Constructor instead of Actual Class Object

Why should I use Interface type of object in Constructor instead of Actual Class Object

Scheduled Pinned Locked Moved ASP.NET
architecturecsharpasp-netregexworkspace
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Amy Dev
    wrote on last edited by
    #1

    I've outsourced my enterprise level project to a freelancer and I got a quite good setup too. But now that contract has finished and the person has also moved to a new technology, in other words not willing to extend the contract. Now I'm looking into this code on myself. I do have a 2 3 years of background in C# and MVC. Below is a rough idea of my application architecture. Hopefully I've tried my best to abstract the architectural details of an enterprise level application. Please let me know if you need further brief on any of the questions. All my Entities are defined as C# POCO classes as:

    public class Product : BaseEntity
    {
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    }

    Now I've a IDbContext like as :

    public interface IDbContext : IDisposable
    {
    IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
    }

    Base Entity is a Partial POCO class that each POCO entity is inheriting. Here is a class that implements this IDBContext as:

    public class MyObjectContext : DbContext, IDbContext
    {
    public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
    {
    return base.Set<TEntity>();
    }
    }

    Now I've defined a IDbContextFactory that is responsible for providing the DBContexts as :

    public interface IDbContextFactory
    {
    Lazy<IDbContext> CreateDbContext();
    }

    The class implementing this IDBContextFactory interface is having below structure :

    public class MyDbContextFactory : IDbContextFactory
    {
    public MyDbContextFactory(string dbConnectionString)
    {
    _dbConnectionString = Settings.DbConnectionString;
    _dbContext = CreateDbContext();
    }

    public IDbContext CreateDbContext()
    {
        IDbContext dbContext = new IDbContext(() => CreateNewContext());
        return dbContext;
    }
    
    private MyObjectContext CreateNewContext()
    {
        return new MyObjectContext (\_dbConnectionString);
    }
    

    }

    Here IRepo Pattern comes into role as:

    public partial interface IRepository<T> where T : BaseEntity
    {
    T GetById(object id);
    }

    Now the Repository class implementing this Interface is as below :

    public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
    private readonly Lazy<IDbContext> _dbContext;
    private readonly IDbContextFactory _dbContextFactory;
    private

    A F E 3 Replies Last reply
    0
    • A Amy Dev

      I've outsourced my enterprise level project to a freelancer and I got a quite good setup too. But now that contract has finished and the person has also moved to a new technology, in other words not willing to extend the contract. Now I'm looking into this code on myself. I do have a 2 3 years of background in C# and MVC. Below is a rough idea of my application architecture. Hopefully I've tried my best to abstract the architectural details of an enterprise level application. Please let me know if you need further brief on any of the questions. All my Entities are defined as C# POCO classes as:

      public class Product : BaseEntity
      {
      public int ProductId { get; set; }
      public string ProductName { get; set; }
      }

      Now I've a IDbContext like as :

      public interface IDbContext : IDisposable
      {
      IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
      }

      Base Entity is a Partial POCO class that each POCO entity is inheriting. Here is a class that implements this IDBContext as:

      public class MyObjectContext : DbContext, IDbContext
      {
      public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
      {
      return base.Set<TEntity>();
      }
      }

      Now I've defined a IDbContextFactory that is responsible for providing the DBContexts as :

      public interface IDbContextFactory
      {
      Lazy<IDbContext> CreateDbContext();
      }

      The class implementing this IDBContextFactory interface is having below structure :

      public class MyDbContextFactory : IDbContextFactory
      {
      public MyDbContextFactory(string dbConnectionString)
      {
      _dbConnectionString = Settings.DbConnectionString;
      _dbContext = CreateDbContext();
      }

      public IDbContext CreateDbContext()
      {
          IDbContext dbContext = new IDbContext(() => CreateNewContext());
          return dbContext;
      }
      
      private MyObjectContext CreateNewContext()
      {
          return new MyObjectContext (\_dbConnectionString);
      }
      

      }

      Here IRepo Pattern comes into role as:

      public partial interface IRepository<T> where T : BaseEntity
      {
      T GetById(object id);
      }

      Now the Repository class implementing this Interface is as below :

      public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
      {
      private readonly Lazy<IDbContext> _dbContext;
      private readonly IDbContextFactory _dbContextFactory;
      private

      A Offline
      A Offline
      Anurag Gandhi
      wrote on last edited by
      #2

      Hi Amy, All the approach provided by you looks good to me. Interface segregation, layered architecture and lazy evaluation all are the sign of good design and practices. Unfortunately, it will take a while for you to understand it properly. I believe that these design principle cannot be understood in a single day. For your answer to why interface, the following articles can answer you partially: Interface based programming in C#[^] http://www.codeproject.com/Articles/54967/Interfaces-In-Action[^] http://www.codeproject.com/Articles/804581/Why-do-we-need-Interfaces[^] For your 3rd question, I would like you to Google on "Lazy Evaluation" to understand this.

      Life is a computer program and everyone is the programmer of his own life.

      1 Reply Last reply
      0
      • A Amy Dev

        I've outsourced my enterprise level project to a freelancer and I got a quite good setup too. But now that contract has finished and the person has also moved to a new technology, in other words not willing to extend the contract. Now I'm looking into this code on myself. I do have a 2 3 years of background in C# and MVC. Below is a rough idea of my application architecture. Hopefully I've tried my best to abstract the architectural details of an enterprise level application. Please let me know if you need further brief on any of the questions. All my Entities are defined as C# POCO classes as:

        public class Product : BaseEntity
        {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        }

        Now I've a IDbContext like as :

        public interface IDbContext : IDisposable
        {
        IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
        }

        Base Entity is a Partial POCO class that each POCO entity is inheriting. Here is a class that implements this IDBContext as:

        public class MyObjectContext : DbContext, IDbContext
        {
        public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
        {
        return base.Set<TEntity>();
        }
        }

        Now I've defined a IDbContextFactory that is responsible for providing the DBContexts as :

        public interface IDbContextFactory
        {
        Lazy<IDbContext> CreateDbContext();
        }

        The class implementing this IDBContextFactory interface is having below structure :

        public class MyDbContextFactory : IDbContextFactory
        {
        public MyDbContextFactory(string dbConnectionString)
        {
        _dbConnectionString = Settings.DbConnectionString;
        _dbContext = CreateDbContext();
        }

        public IDbContext CreateDbContext()
        {
            IDbContext dbContext = new IDbContext(() => CreateNewContext());
            return dbContext;
        }
        
        private MyObjectContext CreateNewContext()
        {
            return new MyObjectContext (\_dbConnectionString);
        }
        

        }

        Here IRepo Pattern comes into role as:

        public partial interface IRepository<T> where T : BaseEntity
        {
        T GetById(object id);
        }

        Now the Repository class implementing this Interface is as below :

        public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
        {
        private readonly Lazy<IDbContext> _dbContext;
        private readonly IDbContextFactory _dbContextFactory;
        private

        F Offline
        F Offline
        F ES Sitecore
        wrote on last edited by
        #3

        Interfaces are used over concrete classes mainly to allow dependency injection and also better unit testing. If your code has neither of these then interfaces might have been used anyway so that if you do use DI or unit testing in the future then you don't have to re-factor all of your code.

        E 1 Reply Last reply
        0
        • F F ES Sitecore

          Interfaces are used over concrete classes mainly to allow dependency injection and also better unit testing. If your code has neither of these then interfaces might have been used anyway so that if you do use DI or unit testing in the future then you don't have to re-factor all of your code.

          E Offline
          E Offline
          Erik Funkenbusch
          wrote on last edited by
          #4

          While it's true that interfaces are useful for these purposes, that's not why they exist or why they are mainly used. Interface Segregation Principle is one of the Five principles of SOLID design, and stands on its own beyond its use in testing or DI. Interfaces are used to decouple implementation from contract and are important in many other patterns and practices. Do not fall into the trap of thinking they are only useful for testing or DI, and they don't need to be used otherwise.

          -- Where are we going? And why am I in this handbasket?

          F 1 Reply Last reply
          0
          • A Amy Dev

            I've outsourced my enterprise level project to a freelancer and I got a quite good setup too. But now that contract has finished and the person has also moved to a new technology, in other words not willing to extend the contract. Now I'm looking into this code on myself. I do have a 2 3 years of background in C# and MVC. Below is a rough idea of my application architecture. Hopefully I've tried my best to abstract the architectural details of an enterprise level application. Please let me know if you need further brief on any of the questions. All my Entities are defined as C# POCO classes as:

            public class Product : BaseEntity
            {
            public int ProductId { get; set; }
            public string ProductName { get; set; }
            }

            Now I've a IDbContext like as :

            public interface IDbContext : IDisposable
            {
            IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
            }

            Base Entity is a Partial POCO class that each POCO entity is inheriting. Here is a class that implements this IDBContext as:

            public class MyObjectContext : DbContext, IDbContext
            {
            public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
            {
            return base.Set<TEntity>();
            }
            }

            Now I've defined a IDbContextFactory that is responsible for providing the DBContexts as :

            public interface IDbContextFactory
            {
            Lazy<IDbContext> CreateDbContext();
            }

            The class implementing this IDBContextFactory interface is having below structure :

            public class MyDbContextFactory : IDbContextFactory
            {
            public MyDbContextFactory(string dbConnectionString)
            {
            _dbConnectionString = Settings.DbConnectionString;
            _dbContext = CreateDbContext();
            }

            public IDbContext CreateDbContext()
            {
                IDbContext dbContext = new IDbContext(() => CreateNewContext());
                return dbContext;
            }
            
            private MyObjectContext CreateNewContext()
            {
                return new MyObjectContext (\_dbConnectionString);
            }
            

            }

            Here IRepo Pattern comes into role as:

            public partial interface IRepository<T> where T : BaseEntity
            {
            T GetById(object id);
            }

            Now the Repository class implementing this Interface is as below :

            public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
            {
            private readonly Lazy<IDbContext> _dbContext;
            private readonly IDbContextFactory _dbContextFactory;
            private

            E Offline
            E Offline
            Erik Funkenbusch
            wrote on last edited by
            #5

            This is a variation of a fairly common way of abstracting your data layer in Unit of Work and Repository patterns. First, let me say there is nothing "enterprise" about this. It's used in both small, medium and large applications. So anyone that told you this was about enterprise development was feeding you a line. Second, this particular implementation is a bit heavy on the abstractions.. and could probably be slimed down, but there is basically nothing wrong with it, other than having to maintain all those extra abstractions. (also, depending on who you talk to, some people feel that generic repositories are a bad idea, and an anti-pattern. I'm one of them, but It is a controversial subject). Third, if you're using Entity Framework as your underlying data model, these abstractions are probably just extra noise since EF already provides these abstractions in the form of your DbContext and DbSet, which are already Unit of Work and Generic Repsitory respectively. You can add interfaces to these to make them more Dependency Injection friendly fairly easily, and as of EF6 they provide mockability so neither DI or Unit testing are good reasons to add the extra abstraction layers anymore. However, some people like the comfort of knowledge that they may want to replace their data layer some day and adding these abstractions (in theory) makes that easier (although in practice it's usually not so simple as these are leaky abstractions which tend to leak into your application layers anyways). However, having said all that.. if you already have this infrastructure, I wouldn't go ripping it out unless you find it to be too burdensome to maintain. Now, on to the interfaces... Yes, you absolutely should be using interfaces. For reasons of Unit testing and Dependency Injection, as well interface segregation principle. Using an interface helps decouple your implementation from the contract you use to access it. It's important to realize that "enterprise architecture" is a lot more than just adding an abstracted data layer. It's creating standards that your enterprise follows, and architecting your suite of applications to work together. It's having an infrastructure or technologies, like Service Busses, or Message Queues and planning redundancy, durability, and failability. In short, it's about seeing the forest and not the trees.

            -- Where are we going? And why am I in this handbasket?

            1 Reply Last reply
            0
            • E Erik Funkenbusch

              While it's true that interfaces are useful for these purposes, that's not why they exist or why they are mainly used. Interface Segregation Principle is one of the Five principles of SOLID design, and stands on its own beyond its use in testing or DI. Interfaces are used to decouple implementation from contract and are important in many other patterns and practices. Do not fall into the trap of thinking they are only useful for testing or DI, and they don't need to be used otherwise.

              -- Where are we going? And why am I in this handbasket?

              F Offline
              F Offline
              F ES Sitecore
              wrote on last edited by
              #6

              Yes I know what they are used for thank you very much. I was trying to give a real-world answer to the real-world question that was posted. The question wasn't "Why should I use an interface" so my answer was not addressing interfaces in general. I didn't say they are only used for DI and unit testing and that they don't need to be used elsewhere.

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups