Windsor,EF和每个请求交易

时间:2014-05-23 09:23:17

标签: entity-framework castle-windsor

所以我正在尝试使用Castle Windsor和Tasks实现每个请求的事务处理。我有theese 2接口

public interface IRunOnEachRequest
    {
        void Execute();
    }

    public interface IRunAfterEachRequest
    {
        void Execute();
    }

在global.asax中,Application_BeginRequest和Application_EndRequest负责从实现theese接口的类中运行所有Execute方法,如下所示:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
      var taskRunner = container.Resolve<RunOnEachRequestTaskRunner>();
      taskRunner.RunAll();
}

protected void Application_EndRequest(Object sender, EventArgs e)
{
     var taskRunner = container.Resolve<RunAfterEachRequestTaskRunner>();
     taskRunner.RunAll();
}

TaskRunners接受IEnumerable任务的依赖

public RunOnEachRequestTaskRunner(IEnumerable<IRunOnEachRequest> tasks)
        {
            _tasks = tasks;
        }

因此,我添加了Windsor Subdependency Resolver,因此可以使用IEnumerable&lt;&gt;作为依赖:

container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

TransactionManager实现两个接口并为每个接口定义函数:

public class TransactionManager : IRunOnEachRequest, IRunAfterEachRequest
    {
        private MainDbContext _context;

        public TransactionManager(MainDbContext context)
        {
            _context = context;
        }

        void IRunOnEachRequest.Execute()
        {

        }

        void IRunAfterEachRequest.Execute()
        {

        }
    }

以下是问题所在:打开应用程序后,我收到此错误:

Can't create component 'Onion1stTry.Tasks.RunAfterEachRequestTaskRunner' as it has dependencies to be satisfied.

'Onion1stTry.Tasks.RunAfterEachRequestTaskRunner' is waiting for the following dependencies:
- Service 'System.Collections.Generic.IEnumerable`1[[Onion1stTry.Tasks.IRunAfterEachRequest, Onion1stTry, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' which was not registered.

似乎,TransactionManager存在问题。如果我只实现一个Execute方法,一切都没问题,但当有两个(每个接口一个)时,我得到了这个错误。

EDIT1:添加了IRunOnEachRequest / IRunAfterEachRequest注册。

container.Register(
                Classes.FromThisAssembly()
                .BasedOn<IRunOnEachRequest>()
                .WithService.FromInterface()
                .LifestylePerWebRequest());

            container.Register(
               Classes.FromThisAssembly()
               .BasedOn<IRunAfterEachRequest>()
               .WithService.FromInterface()
               .LifestylePerWebRequest());

1 个答案:

答案 0 :(得分:0)

万一其他人发现这个有用,以下是我自己的问题的答案:

第一个问题是注册接口。而不是:

.WithService.FromInterface()

我应该用过这个:

.WithService.AllInterfaces()

第二,Application_EndRequest事件。在解决了第一个问题后,我得到了另一个问题 -

Cannot access a disposed object.
Object name: 'Scope cache was already disposed. This is most likely a bug in the calling code.'.

解决方案是从Application_ReleaseRequestState调用相同的代码。