0

My DbContext 구현은 두 개의 인터페이스를 구현합니다. 모범 사례를 따르고 HTTP 요청 당 하나의 DbContext 인스턴스를 인스턴스화하려고합니다. 그러나 컨트롤러 동작을 통해 두 클래스를 인스턴스화해야하는데, 각 클래스는 생성자에서 다른 인터페이스를 사용합니다. 그 시나리오에서 특정 작업에 대해 두 개의 DbContext 인스턴스가 생성 될지 걱정됩니다.Autofac, ASP.NET MVC의 HTTP 요청 당 동일한 구현을위한 다중 인터페이스

내가 설정이처럼 내 ContainerBuilder했습니다 :

 builder.RegisterType<MyDbContext>() 
      .As<IWorkflowPersistenceStore>() 
      .As<IDocumentPersistenceStore>() 
      .InstancePerHttpRequest(); 
    builder.RegisterType<WorkflowManager>().As<IWorkflowManager>().InstancePerHttpRequest(); 
    builder.RegisterType<DocumentManager>().As<IDocumentManager>().InstancePerHttpRequest(); 


public class OperationController : Controller 
{ 
    private IWorkflowManager _workflowManager; 
    private IDocumentManager _documentManager; 

    public OperationController(IWorkflowManager workflowManager, IDocumentManager documentManager) 
    { 
     _workflowManager = workflowManager; 
     _documentManager = documentManager; 
    } 

    public ActionResult SaveWorkflowDocument(...) 
    { 
     // will my managers point to same DbContext? 
     _workflowManager.DoSomething(...); 
     _documentManager.DoSomethingElse(...); 

     return View(); 
    } 
} 

public class WorkflowManager : IWorkflowManager 
{ 
    private IWorkflowPersistenceStore _store; 

    public WorkflowManager(IWorkflowPersistenceStore store) 
    { 
     _store = store; 
    } 
} 

public class DocumentManager : IDocumentManager 
{ 
    private IDocumentPersistenceStore _store; 

    public DocumentManager (IDocumentPersistenceStore store) 
    { 
     _store = store; 
    } 
} 

이 충분인가? .SingleInstance()를 추가해야합니까? 나는 그것이 전체 어플리케이션을위한 싱글 톤을 만들지도 모른다고 걱정한다.

답변

2

나는 당신이 가지고있는 것과 괜찮다고 생각합니다. 시험 합격 :

using Autofac; 
using NUnit.Framework; 

namespace AutofacTest 
{ 
    [TestFixture] 
    public class ScopeTest 
    { 
     [Test] 
     public void Test() 
     { 
      var builder = new ContainerBuilder(); 

      builder.RegisterType<Component>() 
       .As<IServiceA>() 
       .As<IServiceB>() 
       .InstancePerLifetimeScope(); 

      using (var container = builder.Build()) 
      using (var scope = container.BeginLifetimeScope()) 
      { 
       var a = scope.Resolve<IServiceA>(); 
       var b = scope.Resolve<IServiceB>(); 

       Assert.AreEqual(a, b); 
      } 
     } 
    } 

    public interface IServiceA { } 
    public interface IServiceB { } 
    public class Component : IServiceA, IServiceB { } 
} 
+0

굉장, 감사합니다! –

관련 문제