Is injecting service into another service bad prac

2019-08-09 04:17发布

I am creating a web application that is tiered in the following way:

Controller > Service > Repository

So it's following a service and repository pattern.

Let's say I have 2 entities Product and Page like so:

public class Product
{
   public string Name { get; set;}
   public Page Page { get; set; )
}

public class Page
{
   public string Name { get; set;}
}

Each of these entities have a repository like so:

public class ProductRepository
{
   public Product GetProduct(int productId)
   {
      // code
   }
}

public class PageRepository
{
   public Product GetPage(int pageId)
   {
      // code
   }
}

And ofcourse, each of these repositories have a service which a repository will be injected into:

public class ProductService
{
   public bool DoesProductExist (int productId)
   {
      // code
   }
}

public class PageService
{
   public bool CreatePage (int productId, PageRequest page)
   {
      // code
   }
}

The problem I have right now, is that when calling the PageService to create a page, it needs to check if a product exists with the given productId because if not then a page shouldn't be created.

I have the following methods but I don't know if they're the best methods or if theres any better

Method 1

Should I inject ProductService into PageService to use the DoesProductExist() method, because reusable code?

Method 2

Should I inject ProductRepository into my PageService to make my own DoesProductExist() method in PageService (defeating the idea of reusable code)

Method 3

Should I create a cross service something like ProductPageService which would implement both services?

If neither of these are good methods then please feel free to suggest your own

2条回答
\"骚年 ilove
2楼-- · 2019-08-09 05:02
  • Method 1 as is, it would create a dependency between your services.

  • Method 2 it's not a good practice to mix repositories between services.

  • Method 3 it's the best way to go, but instead of "implement both services" I would say "interact with / orchestrate both services". You can extract IProductService and IPageService interfaces and inject them into your "cross service". This way you avoid coupling. You can also use this approach (injecting IProductService into PageService) for Method 1.
查看更多
ら.Afraid
3楼-- · 2019-08-09 05:11

Injection is just the tool.

Is injecting service into another service bad practice?

The primary answer is No, that is fine.

What you should pay attention to is Dependencies. It would be awful to inject a BLL service into a DAL for example. You need a clear picture of layers/tiers/modules and draw the lines of who uses who.

But your chain looks OK.

查看更多
登录 后发表回答