I use in my application Ninject as IoC container. I have bindings for database context, unit of work and repositories. It looks as follows:
// Database
Kernel.Bind<IDbConnection>().To<SqlConnection>();
Kernel.Bind<IDatabaseContext>().To<DapperContext>();
Kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
// Repositories
Kernel.Bind<IUserCommandRepository>().To<UserCommandRepository>();
Now, I want to pass the same instance of DatabaseContext to UnitOfWork and repositories. I found this solution: Ninject: Bind Constructor Argument to Property of Other Object but it does not work for me. When I run this code:
public RegisterCommandHandler(IUnitOfWork unitOfWork, IUserCommandRepository userCommandRepository)
{
_unitOfWork = unitOfWork;
_userCommandRepository = userCommandRepository;
}
UnitOfWork context is different than in repository context. So in my binding class I created local var which gets instance of databaseContext, and I pass this var as constructor parameter into unit of work and repositories. Final code looks like this:
// Database
Kernel.Bind<IDbConnection>().To<SqlConnection>();
Kernel.Bind<IDatabaseContext>().To<DapperContext>();
// Gets database context
var databaseContext = Kernel.Get<IDatabaseContext>();
Kernel.Bind<IUnitOfWork>().To<UnitOfWork>().WithConstructorArgument("context", databaseContext);
// Repositories
Kernel.Bind<IUserCommandRepository>().To<UserCommandRepository>().WithConstructorArgument("context", databaseContext);
It works perfectly, but I'm not sure if it is the best practice of binding dependencies using Ninject :) So my question is, if there is another solution to solve this issue. Best regards,