public class CatalogApiController : ApiController
{
#region Fields
private readonly IProductService _productService;
#endregion
#region Constructor
public CatalogApiController(IProductService productService)
{
this._productService = productService;
}
#endregion
#region Utilities
public T ShallowCopyEntity<T>(T source) where T : class, new()
{
// Get properties from EF that are read/write and not marked witht he NotMappedAttribute
var sourceProperties = typeof(T)
.GetProperties()
.Where(p => p.CanRead && p.CanWrite);
var newObj = new T();
foreach (var property in sourceProperties)
{
// Copy value
property.SetValue(newObj, property.GetValue(source, null), null);
}
return newObj;
}
public ICollection<T> ShallowCopyEntity<T>(ICollection<T> source) where T : class, new()
{
var collection = new List<T>();
foreach (var t in source)
{
collection.Add(ShallowCopyEntity<T>(t));
}
return collection;
}
#endregion
#region Methods
[HttpGet]
public Product GetProductById(int id)
{
return ShallowCopyEntity<Product>(_productService.GetProductById(id));
// fails return _productService.GetProductById(id);
}
[HttpGet]
public ICollection<ProductCategory> GetProductCategoriesById(int id)
{
return ShallowCopyEntity<ProductCategory>(_productService.GetProductById(id).ProductCategories.ToList());
// fails return _productService.GetProductById(id);
}
#endregion
}
The problem is the call to
_productService.GetProductById(id).ProductCategories.ToList()
Results in an ObjectContext Disposed exception. In other words, this code is executing outside the scope of the unit of work of the service, or at least the ObjectContext call. As you can see, I'm referring to the service directly and letting Autofac do its thing, but is... there another level of abstraction (unit of work) where I would have access to the proxies and lazy loading of the Entity Objects?