下面的代码有一个非常简单的演示,其中包含实现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();
}
}
}
}
答案 0 :(得分:5)
您应该从生命周期范围而不是从容器中解析服务。 试试这个:
using (var scope = container.BeginLifetimeScope())
{
var car = scope.Resolve<Car>();
car.Go();
}