0

Autofacの使用方法とライフタイムスコープとの併用に関するドキュメントは見つかりません。ライフタイムスコープとレイジー初期化?

:「タグ一致する 『トランザクション』がいかなるスコープは、インスタンスが要求された範囲 から見えない...」私のコントローラのコンストラクタで

に関するエラーを取得私のアクションで
public HomeController(Lazy<ISalesAgentRepository> salesAgentRepository, Lazy<ICheckpointValueRepository> checkpointValueRepository) 
{ 

     _salesAgentRepository = new Lazy<ISalesAgentRepository>(() => DependencyResolver.Current.GetService<ISalesAgentRepository>()); 
     _checkpointValueRepository = new Lazy<ICheckpointValueRepository>(() => DependencyResolver.Current.GetService<ICheckpointValueRepository>()); 
} 

using (var transactionScope = AutofacDependencyResolver.Current.ApplicationContainer.BeginLifetimeScope("transaction")) 
{ 
    using (var repositoryScope = transactionScope.BeginLifetimeScope()) 
    { 
     // .... 
    } 
} 

生涯スコープはLazyと互換性がないのですか、それとも完全に間違っていましたか?

答えて

5

はい、あなたは間違ったツリーを吠えています。

新しいコントローラが、新しいアプリケーション要求ごとに作成されます。したがって、依存関係の存続期間を別々に管理する必要はありません。

リポジトリの有効期間を有効期間に設定します。トランザクションスコープに対しても同じ操作を行います。

このようにすると、両方のリポジトリに同じtransactionScopeが共有されます。

また、このように、トランザクションはアクションフィルタにコミット移動することができます。

public class TransactionalAttribute : ActionFilterAttribute 
{ 
    private IUnitOfWork _unitOfWork; 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null) 
      _unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>(); 

     base.OnActionExecuting(filterContext); 
    } 

    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     if (filterContext.Controller.ViewData.ModelState.IsValid && filterContext.HttpContext.Error == null && _unitOfWork != null) 
      _unitOfWork.SaveChanges(); 

     base.OnActionExecuted(filterContext); 
    } 
} 

(のTransactionScopeでIUnitOfWorkを交換してください)。出典:http://blog.gauffin.org/2012/06/05/how-to-handle-transactions-in-asp-net-mvc3/

+1

ウェブAPIフィルタの場合。文脈からそれを解決してください。 'filterContext.Request.GetDependencyScope()。GetService(typeof(IUnitOfWork))をIUnitOfWork'として実行します。それ以外の場合は、ルートコンテナから解決され、要求内の同じインスタンスにはなりません。 Web APIはキャッシュされたシングルトンをフィルタリングするためです。 –