控制台应用程序C#中的Unity 2 IDisposable问题

时间:2013-03-31 13:38:01

标签: c# unity-container

我在控制台应用程序中使用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。是否有透明的方式处理IDispose对象,如Unity.MVC。或者将来的其他工具。

1 个答案:

答案 0 :(得分:0)

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

在构建的LifetimeManager实现中,只有ContainerControlledLifetimeManager在处置容器本身时才会释放托管对象。

您可以在此处阅读有关终身经理的信息:Understanding Lifetime Managers

如果您的目标是在使用后处置CarRepository,那么您可以使用HierarchicalLifetimeManagerchild containers来实现它:

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**
}