Is injecting service into another service bad practice?

怎甘沉沦 提交于 2019-12-22 11:34:01

问题


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


回答1:


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.




回答2:


  • 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.


来源:https://stackoverflow.com/questions/56552233/is-injecting-service-into-another-service-bad-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!