gpt4 book ai didi

c# - 为什么 Autofac 不调用我的类' `Dispose()` ?

转载 作者:行者123 更新时间:2023-12-02 00:48:28 25 4
gpt4 key购买 nike

下面的代码有一个非常简单的演示,其中的组件实现了IDisposable。不幸的是,实际上没有一个析构函数被调用。谁能告诉我为什么?

using System;
using System.Collections.Generic;
using Autofac;

namespace AutofacDemos
{
public interface ILog : IDisposable
{
void Write(string message);
}

public class ConsoleLog : ILog
{
public void Write(string message)
{
Console.WriteLine(message);
}

// needed for demonstrating ExternallyOwned()
public void Dispose()
{
Console.WriteLine("Console logger no longer required");
}
}

public class Engine
{
private readonly ILog log;

public Engine(ILog log)
{
this.log = log;
}

public void Ahead(int power)
{
log.Write($"Engine ahead {power}");
}
}

public class Car : IDisposable
{
private readonly Engine engine;
private readonly ILog log;

public Car(Engine engine)
{
this.engine = engine;
}

// constructor with most arguments used by default
public Car(Engine engine, ILog log)
{
this.engine = engine;
this.log = log;
}

public void Go()
{
engine.Ahead(100);
log.Write("Car going forward...");
}


public void Dispose()
{
log.Dispose();
}
}

internal class Program
{
public static void Main(string[] args)
{
// var log = new ConsoleLog();
// var engine = new Engine(log);
// var car = new Car(engine, log); // dependencies

var builder = new ContainerBuilder();
//builder.RegisterType<ConsoleLog>().As<ILog>();
var log = new ConsoleLog();
builder.RegisterInstance(log).As<ILog>().ExternallyOwned();

//builder.RegisterType<Engine>();
builder.RegisterType(typeof(Engine));

builder.RegisterType<Car>();

// use the engine-only constructor
//builder.RegisterType<Car>().UsingConstructor(typeof(Engine));

//builder.RegisterTypes(typeof(Car), typeof(Engine));

var container = builder.Build();

var car = container.Resolve<Car>();

using (container.BeginLifetimeScope())
{
car.Go();
}


}
}
}

最佳答案

您应该从生命周期范围而不是容器中解析您的服务。试试这个:

using (var scope = container.BeginLifetimeScope())
{
var car = scope.Resolve<Car>();
car.Go();
}

关于c# - 为什么 Autofac 不调用我的类' `Dispose()` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41923490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com