If I have two controllers:
public class PrimaryController : Controller
{
private IRepository<Primaries> repository;
public PrimaryController(IRepository<Primaries> repository)
{
this.repository = repository;
}
// CRUD operations
}
and
public class AuxiliaryController : Controller
{
private IRepository<Primaries> repository;
public AuxiliaryController(IRepository<Primaries> repository)
{
this.repository = repository;
}
// CRUD operations
public ActionResult CreateSomethingAuxiliary(Guid id, AuxiliaryThing auxiliary)
{
var a = repository.Get(id);
a.Auxiliaries.Add(auxiliary);
repository.Save(a);
return RedirectToAction("Details", "Primary", new { id = id });
}
}
and DI is implemented like (code is from a Ninject module)
this.Bind<ISessionFactory>()
.ToMethod(c => new Configuration().Configure().BuildSessionFactory())
.InSingletonScope();
this.Bind<ISession>()
.ToMethod(ctx => ctx.Kernel.TryGet<ISessionFactory>().OpenSession())
.InRequestScope();
this.Bind(typeof(IRepository<>)).To(typeof(Repository<>));
will this work properly? I mean will controllers use the same repository instance?
Thanks!
Simple answer – yes! Code will use same implementation for all controllers unless you explicitly configure otherwise, using
When...methods.If you want to reuse not implementation, but same instance of object, you could configure that using methods like
InScope,InRequestScope,InSingletonScopeas you already do for ISession and ISessionFactory.From documentation:
Using
Repositoryin singleton is not a good Idea. I useInRequestScopeto make one instance serve just one request. If using entity framework, you could check out this answer for details