I have some problem with IoC - Unity.
I made a simple web app. It consists of one Table "Post" which have three fields: PostId, title, Text. I use generic repository:
public abstract class BaseRepository<T> : IBaseRepository<T> where T : class
{
protected ObjectContext db = new BlogDbEntities();
/* CRUD */
}
public class PostRepository : BaseRepository<Post>, IPostRepository
{
public void Search(Expression<Func<Post, object>> predicate)
{
/* some search specific entity logic */
}
}
public interface IPostRepository : IBaseRepository<Post>
{
void Search(Expression<Func<Post, object>> predicate);
}
int that repository as you see i create new BlogDbEntities - ObjectContext. And in controller i use IPostRepository, controller is very simple:
public class PostController : Controller
{
IPostRepository postRepository;
public PostController(IPostRepository postRepository)
{
this.postRepository = postRepository;
}
public ActionResult Index()
{
postRepository.All.ToList();
return View();
}
protected override void Dispose(bool disposing)
{
postRepository.Dispose();
base.Dispose(disposing);
}
}
And in Global.asax i resolve dependencies with Unity:
var container = new UnityContainer();
var controllerFactory = new UnityControllerFactory(container);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
container.RegisterType<IPostRepository, PostRepository>(new ContainerControlledLifetimeManager());
After starting application when i do request for example /Post/ first request executed normally. But when i try to execute request again i get Exception "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."
When i try to execute request without Unity IoC framework exception not displayed and ObjectContext work normally.
I guess that cause of that behavior is Unity, i think that context stored in Unity Container. Who can help me how to properly configure Unity with recreating context after each request.