小编Mar*_*lta的帖子

AutoFac 委托工厂和生命周期范围

我在我的应用程序中使用委托工厂。那是因为我使用 AutoFac 创建的组件使用需要一些参数的服务类。

我想做的下一件事是使用 AutoFacs 生命周期范围机制正确清理这些服务并释放资源。然而问题是,当我使用委托工厂创建组件时,它们似乎没有被放入生命周期范围,并且在处置生命周期范围后不会调用 Dispose。

我想避免使用通用的 Owned<>,因为我不想将我的应用程序绑定到特定的 IOC。

http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/中解释了委托工厂创建的组件被放入与委托工厂相同的生命周期范围中。

我写了一个小程序来演示这一点。在此程序中,我希望调用 Dispose 函数。不幸的是这并没有发生。我想念这里吗?下面的代码有什么问题吗?如何确保委托工厂生产的组件被放入委托工厂的生命周期范围内?

using Autofac;
using Autofac.Core;
using System;

namespace FactoryTest
{
class Component : IDisposable
{
    public Component(int i) { }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();

        builder.Register<Func<int, Component>>(c => (x) =>
        {
            // code that is important and that should run
            // inside the delegate factory.
            return new Component(x); …
Run Code Online (Sandbox Code Playgroud)

c# autofac

5
推荐指数
1
解决办法
1926
查看次数

标签 统计

autofac ×1

c# ×1