StructureMap:在特定上下文中自定义生存期范围

本文关键字:自定义 生存期 范围 上下文 StructureMap | 更新日期: 2023-09-27 18:26:46

我有几个循环,每个循环都通过ConcurrentQueue<T>生成异步进程。这些流程调用一些业务服务实现,这些业务服务实现使用存储库进行数据库交互。服务实现都是通过StructureMap连接起来的。

存储库实现具有一些需要仔细管理的特性:

  • 正在使用的数据库技术是Redis
  • 该实现使用ServiceStack.net的Redis客户端(通过PooledRedisClientManager
  • 有几种方法使用的事务(我相信)不能由同一个RedisClient同时创建。因此,在多个异步进程上共享单个存储库实现是不可能的,因为它会试图同时创建多个事务
  • 为了释放内存和数据库连接,需要显式地处理这些对象——因此,我在存储库类上实现了IDisposable
  • 没有理由不能在单个异步进程的范围内共享存储库实例,因为不会有并发请求/事务

考虑到以上内容,我想将单个存储库实例的范围限定为每个异步进程的生存期。

需要记住的一件事是,异步进程范围内使用的服务也被系统中具有不同生存期特征的其他部分使用(例如,在存储库范围为页面请求生存期的网站中)。

我将尝试用一些代码(从我的代码中简化)来说明:

管理队列的程序(并连接执行IAsyncResult调用的事件处理程序):

public class Program
{
    private readonly ConcurrentQueue<QueueItem> queue = new ConcurrentQueue<QueueItem>();
    private readonly IItemManager itemManager; // implemented via constructor DI.
    public void ProcessQueueItems()
    {
        while ( queue.Count > 0 || shouldContinueEnqueuing )
        {
            QueueItem item;
            if ( queue.TryDequeue( out item ) )
            {
                // Begin async process here - only one repository should be used within the scope of this invocation
                // (i.e. withing the scope of the itemManager.ProcessItem( item ) method call.
                new ItemProcessor( itemMananger.ProcessItem ).BeginInvoke( e.Item, ItemCallback, null );
            }
            Thread.Sleep( 1 );
        }
    }
    private static void ItemCallback( IAsyncResult result )
    {
        var asyncResult = ( AsyncResult ) result;
        var caller = ( ItemProcessor ) asyncResult.AsyncDelegate;
        var outcome = caller.EndInvoke( result );
        // Do something with outcome...
    }
    private delegate ItemResult ItemProcessor( QueueItem item );
}

异步结果调用的实现。我想在ProcessItem( ... )方法中管理范围:

public class ItemManager : IItemManager
{
    private readonly IServiceA serviceA; // implemented via constructor DI.
    private readonly IServiceB serviceB; // implemented via constructor DI.
    public ItemResult ProcessItem( QueueItem item )
    {
        // Both serviceA and serviceB use the repository which is injected via StructureMap. They should share 
        // the instance and at the end of the process it should be disposed (manually, if needs be).
        var something = serviceA.DoSomething( item );
        return serviceB.GetResult( something );
    }
}

我认为这可以解释情况和目标。我的问题如下:

  1. 我可以使用StructureMap在如上所述的单个流程的上下文中使用不同的范围吗
  2. 我不想在我的域/服务层中包含对StructureMap的直接依赖。那么,如果我能够在这个阶段使用不同的范围,那么有没有一种简单的方法可以做到这一点,而无需从流程本身直接调用StructureMap
  3. 我可以通过DSL配置指示StructureMap在过程结束时处理存储库吗?或者我需要在代码中明确这样做吗

StructureMap:在特定上下文中自定义生存期范围

您可以在这种情况下使用嵌套容器。

嵌套容器将跟踪它所在的所有瞬态对象创建。当嵌套容器本身被释放时,它将调用对它创建的任何瞬态对象执行Dispose()。

var nestedContainer = container.GetNestedContainer();
var processor = nestedContainer.GetInstance<IItemProcessor>();

确保每个对象使用相同存储库的另一种方法是使用With()方法

// Get the IRepository which should be shared   
// This object is registered using simple
// For<ISession>.Use<Session> registration so not scoped
// http context or anything like that
var session = container.GetInstance<ISession>();
// Create instance of IProcessor using the specific instance
// of ISession. If multiple classes in the object grap use ISession
// they will get the same instance. Note that you can use multiple
// With() statements
var itemProcessor = container.With(session).GetInstance<IItemProcessor>();