0

UnitOfWork 및 Repository 패턴 외에도 Unity를 IoC로 사용하고 싶습니다. 나는 다양한 관련 기사와 질문을 읽었지 만 그들 중 누구도 나를 완전히 만족시키지 못했습니다. 모든 접근 방식에 문제가 있습니다. 예를 들어 내 문제를 더 잘 설명 할 수 있습니다.Unity를 사용하여 두 저장소간에 UnitOfWork를 공유하는 가장 좋은 방법은 무엇입니까?

두 개의 다른 클래스 (비즈니스 서비스 일 수도 있음)에서 두 개의 리포지토리로 작업하기를 원하지만 전반적인 작업은 하나의 단위로 이루어집니다.

시작 지점은 LocalService1.Method1 메서드입니다.

public class LocalService1 
{ 
    public void Method1(int id) 
    { 
     var repository1 = Container.Current.Resolve<IRepository1>(); // Injects the IUnitOfWork for the repository. 
     var entity1 = repository1.GetEntity1(id); 
     var service2 = Container.Current.Resolve<LocalService2>(); // Maybe it’s better not to use IoC for business logic. This is not my issue. 
     service2.Method2(entity1) 
    } 
} 
... 
public class LocalService2 
{ 
    public void Method2(Entity1 entity1) 
    { 
     var repository2 = Container.Current.Resolve<IRepository2>(); // Injects the IUnitOfWork for the repository. 
     var count = repository2.GetEntity2sCount(entity1.Id); 
     // Do some works with count and entity1 
    } 
} 

주요 질문

"는 LocalService1.Method1를 호출하는 동안 나는의 UnitOfWork를 공유 할 수있는 방법 IRepository1 및 IRepsitory2 사이 (여기 ObjectContext를 할 수 있습니다)?"는 것이다. 더 중요한 것은 "UnitOfWork 폐기에 대해 확신하고 싶습니다."입니다.

나는 대답 이러한 문제에 초점을 맞출 것 같아요 (? 방법 등)

  • IOC의 구성
  • 생활 시간 구성
  • 처리 시간

If "HttpContext"사용을 권장합니다. 비 웹 환경을 고려하십시오.

나는 내 질문에 대해 거의 알고있다 "생활 시간 관리"하지만 철저한 접근 방법을 찾고 있어요.

답변

1

먼저 : Unity를 ServiceLocator로 사용하지 마십시오. 이것은 considered an anti-pattern입니다. 대신 constructor injection을 사용하십시오.

Unity의 LifetimeManagers는 자체적으로 치료하지 않습니다. 이 기능은 wish list for Unity vNext에 있습니다.

개체를 폐기하려는 경우 create your own LifetimeManager과 관련하여 BuilderStrategy을 정리해야합니다.

Mark Seemann의 저서 종속성 삽입에서 가져온 TecX project (TecX.Unity.Lifetime 내부)에 샘플이 있습니다.