Correct way to inject dependencies in Business logic service?

Posted by Sri Harsha Velicheti on Programmers See other posts from Programmers or by Sri Harsha Velicheti
Published on 2014-05-19T18:28:43Z Indexed on 2014/08/20 16:35 UTC
Read the original article Hit count: 210

Currently the structure of my application is as below Web App --> WCF Service (just a facade) --> Business Logic Services --> Repository -> Entity Framework Datacontext

Now each of my Business logic service is dependent on more than 5 repositories ( I have interfaces defined for all the repos) and I am doing a Constructor injection right now(poor mans DI instead of using a proper IOC as it was determined that it would be a overkill for our project). Repositories have references to EF datacontexts. Now some of the methods in the Business logic service require only one of the 5 repositories, so If I need to call that method I would end up instantiating a Service which will instatiate all 5 repositories which is a waste. An example:

public class SomeService : ISomeService
{
   public(IFirstRepository repo1, ISecondRepository repo2, IThirdRepository repo3)
   {}

   // My DoSomething method depends only on repo1 and doesn't use repo2 and repo3
   public DoSomething()
   {
        //uses repo1 to do some stuff, doesn't use repo2 and repo3
   }   

   public DoSomething2()
   {
     //uses repo2 and repo3 to do something, doesn't require repo1
   }

   public DoSomething3()
   {
     //uses repo3 to do something, doesn't require repo1 and repo2
   }
}

Now if my I have to use DoSomething method on SomeService I end up creating both IFirstRepository,ISecondRepository and IThirdRepository but using only IFirstRepository, now this is bugging me, I can seem to accept that I am un-necessarily creating repositories and not using them.

Is this a correct design? Are there any better alternatives? Should I be looking at Lazy instantiation Lazy<T> ?

© Programmers or respective owner

Related posts about c#

Related posts about design-patterns