First, I have a dbcontext factory which is defined public class DatabaseFactory : Disposable, IDatabaseFactory
and it just creates a context if one doesn't already exist.
Next, I have a generic repository that is defined public class Repository<T> : IRepository<T>
where T : class
which takes the factory in the constructor. I have other concrete repositories that inherit from this one.
I also have a unit of work class that is defined public class UnitOfWork : IUnitOfWork
which takes the factory in the constructor and saves all changes to the context inside the factory (which all repositories should be using).
In my controller, I have the constructor set as public ProjectController(IDatabaseFactory factory, IUnitOfWork unitOfWork, IProjectRepository projectRep, IUserRepository userRep)
.
Basically, I need the same instance of the factory to be passed to the unit of work and all repositories. With ninject, it creates a new factory for each object instead of passing a single instance to them all. Is there a way to only allow the single instance to be passed via ninject or am I not creating my factory correctly and/or not understanding ninject correctly?
Here are my bindings in ninject:
kernel.Bind<IProjectRepository>().To<ProjectRepository>();
kernel.Bind<IIssueRepository>().To<IssueRepository>();
kernel.Bind<IUserRepository>().To<UserRepository>();
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
This happens because by default Ninject
uses the Transient
scope - which creates a new instance every time a type is requested.
More info: https://github.com/ninject/ninject/wiki/Object-Scopes
You should specify the scope depending on the actual usage of a particular instance of a type throughout your application:
Example could look like this:
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>().InSingletonScope();
kernel.Bind<IUserRepository>().To<UserRepository>().InRequestScope();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With