1

When I try to create a new IRepository<Tag> using kernel.Get, Ninject throws an exception. Am I using Ninject in the correct manner and are the bindings set up correctly?

Method of class NinjectDependencyResolver:

private void AddBindings()
        {
            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new TagProfile());
            });
            var mapper = mapperConfiguration.CreateMapper();
            _kernel.Bind<BlogDbContext>().ToSelf().InRequestScope();
            _kernel.Bind<IRepository<Tag>, Repository<Tag>>();
            _kernel.Bind<IMapper>().ToConstant(mapper);

            var repository = _kernel.Get<IRepository<Tag>>(); // exception thrown here
            _kernel.Bind<ITagService, TagService>();
        }

Class Repository:

`public class Repository<T> : IRepository<T> where T : class
{
    private readonly BlogDbContext _db;

    public Repository(BlogDbContext db)
    {
        _db = db;
    }
}`

P.S.. I do not know whether this is important, but its interface repository is located in the same assembly, and Ninject registration in another.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Lightness
  • 261
  • 1
  • 11
  • You are binding the `BlogDbContext` in request scope, but when you call `AddBindings`, are you in a request scope? – mason Jan 26 '17 at 19:13
  • @mason, Sorry, I do not understand what you mean. But when I try `InSingletonScope() ` all works well. But Singleton would not want to use. – Lightness Jan 26 '17 at 19:19
  • A request is an HTTP request, like a client accessing a page. When scoping the lifetime of your dependencies, you can have the object be alive for just that particular request, which is how you have it now. But that means that dependency won't be able to be resolve outside of a request, so later when it tried to get an `IRepository` it can't satisfy the constructor for `Repository`. Or at least that's my guess as to what's going on. – mason Jan 26 '17 at 19:22

1 Answers1

2

Your binding syntax is incorrect. Change:

_kernel.Bind<IRepository<Tag>, Repository<Tag>>();

To:

_kernel.Bind<IRepository<Tag>>.To<Repository<Tag>>();
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64