在中介模式实现中将 Ninject 注入处理器以进行对象解析

Injecting Ninject into a Processor for Object Resolution in Mediator Pattern Implementation

我遇到了内存泄漏问题,我找不到解决办法。它适用于桌面应用程序,而不是 Web,因此对象的生命周期比单个请求长。

我正在尝试实现这个优秀博客中描述的架构 post - https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92

QueryProcessor class 需要 IOC 容器,因为它在调用 Process 方法时解析具体类型。我的实现如下所示:

public sealed class QueryProcessor : IQueryProcessor, IDisposable
{
    private readonly IKernel _container;
    private bool _disposed;

    public QueryProcessor(IKernel container)
    {
        _container = container;
    }

    //[DebuggerStepThrough]
    public TResult Process<TResult>(IQuery<TResult> query)
    {
        var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));

        dynamic handler = (_container.Target as IKernel).Get(handlerType);

        return handler.Handle((dynamic)query);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (disposing && !_disposed)
        {
            // dispose container ???
            _disposed = true;
        }            
    }
}

我遇到的问题是,如果我注入 Ninject 内核,这意味着 QueryProcessor class 在运行时不会被垃圾收集超出范围,因为它维护对内核的引用。

如果我丢弃它,并在内核上调用 Dispose,我已经杀死了我的内核并且没有更多的应用程序 DI。

如果我创建一个单独的内核并为 QueryProcessor 的每个实例注入它,那么 Ninject 一旦它尝试解析具体类型就会抛出一个异常 - “加载错误 Ninject 组件 ICache”。显然 Ninject 不喜欢超过 1 个内核。

有什么方法可以让 class 拥有一个成员并在它被垃圾回收之前释放该成员?

The problem I am having is that if I inject the Ninject kernel, it means the QueryProcessor class does not get garbage collected when it goes out of scope, as it maintains a reference to the kernel.

当没有任何对象引用该对象时,该对象符合垃圾回收条件。此对象引用的其他对象无关紧要。所以也许你在错误的地方寻找内存泄漏。我看到您没有注册 IKernel 的任何事件(这会创建一个从 IKernel 委托到您的对象的引用)所以如果没有其他引用您的 QueryProcessor 它应该被垃圾收集。