我在控制台应用程序中使用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。或者将来的其他工具。
答案 0 :(得分:0)
RegisterType
方法默认使用TransientLifetimeManager
,它不存储对创建对象的引用,因此它不会为您调用Dispose
。
在构建的LifetimeManager
实现中,只有ContainerControlledLifetimeManager
在处置容器本身时才会释放托管对象。
您可以在此处阅读有关终身经理的信息:Understanding Lifetime Managers
如果您的目标是在使用后处置CarRepository
,那么您可以使用HierarchicalLifetimeManager
和child 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**
}