Unity 2 IDisposable Issue in Console Application C#

本文关键字:Console Application in Issue IDisposable Unity | 更新日期: 2023-09-27 18:06:57

我在控制台应用程序中使用Unity 2.1.505.0,该应用程序由IDisposable实现CarRepository组成。但是,Dispose()在其作用域之外时永远不会被调用。以下是代码示例:

    internal class Program
    {
        private static void Main(string[] args)
        {           
            CarShop.Entry();
        }
    }
    class CarShop
    {
       static UnityContainer unityContainer = new UnityContainer();
        public static void Entry()
        {           
            unityContainer.RegisterType<ICarRepository, CarRepository>();
            var carShop = new CarShop();
            carShop.BuyCar();
        }
      public void BuyCar()
      {
          CheckCar();
      }
      private void CheckCar()
      {
          var carService = unityContainer.Resolve<CarService>();
          var car = carService.GetCar(1);  
         // **Dispose() method is not called out of this scope**
      }
    }
   class CarService
    {
        private ICarRepository carRepository;
        public CarService(ICarRepository carRepository)
        {
            this.carRepository = carRepository;
        }
        public Car GetCar(int id)
        {
            return this.carRepository.GetCar(id);
        }
    }
    interface ICarRepository
    {
        Car GetCar(int id);
    }
    class CarRepository : ICarRepository, IDisposable
    {
        public Car GetCar(int id)
        {
            return null;
        }
        public void Dispose()  
        {
        }
    }
    public class Car
    {
    }

知道吗??

更新

正如@nemesv建议的解决方案如下:

unityContainer.RegisterType<ICarRepository, CarRepository>(
        new HierarchicalLifetimeManager())
 using (var childContainer = unityContainer.CreateChildContainer())
    {
        var carService = childContainer.Resolve<CarService>();
        var car = carService.GetCar(1);            
    }

它有效。但与Unity.MVC不同,它需要显式创建childContainer。有没有像Unity这样透明的方式来处理IDispose对象。MVC。或者将来的其他工具。

Unity 2 IDisposable Issue in Console Application C#

默认情况下,RegisterType方法使用TransientLifetimeManager,该方法不存储对创建对象的引用,因此不会为您调用Dispose

在构建的LifetimeManager实现中,只有ContainerControlledLifetimeManager在容器本身被处置时处置被管理对象。

你可以在这里阅读关于终身经理人的文章:了解终身经理人

如果您的目标是在使用后处理CarRepository,那么您可以使用HierarchicalLifetimeManager和子容器来实现:

public static void Entry()
{           
    unityContainer.RegisterType<ICarRepository, CarRepository>(
        new HierarchicalLifetimeManager());
    var carShop = new CarShop();
    carShop.BuyCar();
}
private void CheckCar()
{
    using (var childContainer = unityContainer.CreateChildContainer())
    {
        var carService = childContainer.Resolve<CarService>();
        var car = carService.GetCar(1);            
    }
    // **Dispose() method is not called out of this scope**
}