C# Design Patterns – Correct Way to Inject Dependencies in Business Logic Service

cdesign-patternsentity-frameworkrepository

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> ?

Best Answer

ISP states:

no client should be forced to depend on methods it does not use

Although you are using all the methods from the 5 repositories, you are probably using them in different contexts and probably from different instances of the service (it's hard to figure out the usage scenario from the generic code sample you provided).

Also, your services seem to be doing more than one thing and should be broken down into smaller components (having 4 or more dependencies is often an indication of breaking SRP).

Advice: you should give DI a try. It's definitely not an overkill and you'll have some benefits out of it.