Nice programing

내 MVC 애플리케이션에 대한 서비스 계층을 생성합니까?

nicepro 2020. 10. 18. 19:31
반응형

내 MVC 애플리케이션에 대한 서비스 계층을 생성합니까?


내가 이해 한 바에 따르면 MVC는 컨트롤러 인 "접착제"를 통해 프레젠테이션 (보기)에서 클래스 정의 (모델)를 분리합니다. 컨트롤러는 단일 책임을 가져야하므로 테스트 할 수 있어야합니다. ViewModel은 여러 엔터티의 데이터를 모으고 뷰에 대한 컨트롤러의 데이터를 "마사지"하는 데 사용됩니다.

비즈니스 로직에는 실제로 자리가없는 것 같습니다. 그래서 서비스를위한 다른 계층이 적합 할 것이라고 생각합니다. 이 레이어를 어디에 배치해야하는지, 또는 서비스를 구축하는 방법을 모르겠습니다. 여러 기능을 포함하는 "서비스"라는 클래스 여야합니까? 나는 MVC를 처음 접했기 때문에 어떤 독서 자료, 샘플 또는 일반적인 신참 팁이 굉장 할 것입니다.


ASP.NET MVC 응용 프로그램을 개발할 때 일반적으로 서비스 계층을 사용합니다. Martin Fowler가 Patterns of Enterprise Application Architecture 에서 논의한 서비스 계층 패턴 과 유사합니다 . 비즈니스 로직을 캡슐화하고 컨트롤러를 매우 얇게 만듭니다. 기본적으로 컨트롤러는 서비스 계층을 사용하여 도메인 모델을 가져온 다음 뷰 모델로 변환합니다. 또한 작업 단위 디자인 패턴사용하여 트랜잭션을 처리하고 리포지토리 디자인 패턴 을 사용하여 데이터 액세스 계층을 캡슐화하여 더 쉽게 단위 테스트를 수행하고 ORM을 쉽게 교체 할 수 있습니다. 이 그림은 MVC 애플리케이션에서 사용하는 일반적인 레이어를 보여줍니다.

MVC 아키텍처

서비스 계층은 "서비스 계층"이라는 용어를 사용할 때 사람들이 혼란스러워하기 때문에이 다이어그램에서 "응용 프로그램 또는 도메인 계층"으로 레이블이 지정됩니다. 그들은 이것이 웹 서비스라고 생각하는 경향이 있습니다. 실제로 ASP.NET Web API 또는 WCF와 같은 좋아하는 웹 서비스 기술과 컨트롤러에서 사용할 수있는 어셈블리입니다.

명명 규칙에 관해서는 일반적으로 서비스 다음에 도메인을 설명하는 것을 사용합니다. 예를 들어, 사용자 멤버십을 처리하는 서비스 계층이있는 경우 멤버십 도메인을 쿼리하고 조작하기 위해 컨트롤러 및 웹 서비스에 필요한 모든 메서드를 포함하는 MembershipService라는 클래스가 있습니다. 동일한 애플리케이션에 여러 도메인이있을 수 있으므로 여러 서비스 계층을 가질 수 있습니다. 내 요점은 전체 애플리케이션을 처리하는 하나의 모 놀리 식 서비스가 필요하지 않다는 것입니다.


My advice is to create a separate classes called "services". Put them in different class library (or namespace) project and make them independent on MVC framework infrastructure. I recommend to use also some kind of dependency injection (the best is constructor injection). Then your service classes may look like:

 public class MyService : IMyService
 {
     IFirstDependency _firstService;
     ISecondDependency _secondService;

     public MyService(IFirstDependency firstService, ISecondDependency secondService)
     {
     }

     public Result DoStuf(InputDTO)
     {
         // some important logic         
     }
 }

Then you consume these service from your controllers. Look here for complete example.

According Repositories - my advice is to do not use them if you are going to use some modern ORM (NHibernate, EntityFramework), because your business logic will be encapsulated in the Service Layer and your database will be already encapsulated with the ORM framework.


Take a look at the article from MSDN best practices.

Source code of the application in article can be found here.


Quoting from “Business logic should be in a service, not in a model”?:

In an MVP/MVC/MVVM/MV* architecture, services don't exist at all. Or if they do, the term is used to refer to any generic object that can be injected into a controller or view model. The business logic is in your model. If you want to create "service objects" to orchestrate complicated operations, that's seen as an implementation detail. A lot of people, sadly, implement MVC like this, but it's considered an anti-pattern (Anemic Domain Model) because the model itself does nothing, it's just a bunch of properties for the UI.

Some people mistakenly think that taking a 100-line controller method and shoving it all into a service somehow makes for a better architecture. It really doesn't; all it does is add another, probably unnecessary layer of indirection. Practically speaking, the controller is still doing the work, it's just doing so through a poorly named "helper" object. I highly recommend Jimmy Bogard's Wicked Domain Models presentation for a clear example of how to turn an anemic domain model into a useful one. It involves careful examination of the models you're exposing and which operations are actually valid in a business context.


Sounds like you'd be after something like a repository pattern. You can read about it here:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net- mvc 응용 프로그램

이 답변이 도움이 될 수도 있습니다.

ASP.NET MVC를위한 최상의 리포지토리 패턴

참고 URL : https://stackoverflow.com/questions/14887871/creating-a-service-layer-for-my-mvc-application

반응형