My project is using MVC5, EF6 and Ninject.
I have some service classes which composes the business layer, and only them are allowed to access the DbContext, meaning that the controller doesn't have any direct access to the context.
The service classes are like those:
public interface IService1: IDisposable
{
IEnumerable<SomeDataType> GetSomeData(string param);
void SaveData();
}
public class Service1: IService1
{
private MyContext context;
public Maestri(MyContext context)
{
this.context = context;
}
public void Dispose()
{
context.Dispose();
}
public IEnumerable<SomeDataType> GetSomeData(string Param)
{
[...]
}
public void SaveData()
{
[...]
context.SaveChanges()
}
}
public interface IService2: IDisposable
{
IEnumerable<SomeDataType2> GetSomeData(string param);
void SaveData();
}
public class Service2: IService2
{
private MyContext context;
public Maestri(MyContext context)
{
this.context = context;
}
public void Dispose()
{
context.Dispose();
}
public IEnumerable<SomeDataType2> GetSomeData(string Param)
{
[...]
}
public void SaveData()
{
[...]
context.SaveChanges()
}
}
In Ninject CreateKernel are initialized like this:
kernel.Bind<MyContext>().ToSelf().InRequestScope();
kernel.Bind<IService1>().To<Service1>().InRequestScope();
kernel.Bind<IService2>().To<Service2>().InRequestScope();
In the controller:
public class MyController : Controller
{
private readonly IService1 _service1;
private readonly IService2 _service2;
public MyController(IService1 service1, IService2 service2)
{
_service1 = service1;
_service2 = service2;
}
public ActionResult SomeAction()
{
var data1 = _service1.GetSomeData("");
var data2 = _service2.GetSomeData("");
[...]
return View();
}
}
I've noticed that for every request to Controller/SomeAction the MyContext constructor has called only once, but the dispose() will be called twice. This leads me to think about a bad design of mine. I've tried to remove the context.Dispose(); from the services, but this leads to MyContext.dispose to never get called, but a new instance is generated for every request. Could someone please point me out what am I doing wrong?
Thanks!