Ninject - Injecting singleton
Asked Answered
S

1

1

I have this error when clicking a link on a site I'm creating

Error activating IEntityCache using binding from IEntityCache to EntityCache
No constructor was available to create an instance of the implementation type.

Activation path:
 4) Injection of dependency IEntityCache into parameter entityCache of constructor of type AlbumRepository
 3) Injection of dependency IAlbumRepository into parameter albumRepository of constructor of type AlbumService
 2) Injection of dependency IAlbumService into parameter albumService of constructor of type AlbumController
 1) Request for AlbumController

Suggestions:
 1) Ensure that the implementation type has a public constructor.
 2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.

EntityCache is a singleton with no public construction. So this is how I've done my Ninject bindings

kernel.Bind<IAlbumService>().To<AlbumService>();
            kernel.Bind<IAlbumRepository>().To<AlbumRepository>();
            kernel.Bind<IDbSetWrapper<Album>>().To<DbSetWrapper<Album>>();
            kernel.Bind<IEntityCache>().To<EntityCache>().InSingletonScope();

What am I doing wrong?

EDIT

Here's my repository:

public AlbumRepository(DatabaseContext context, IDbSetWrapper<Album> dbSetWrapper, IEntityCache entityCache)
            : base(context, dbSetWrapper, entityCache)

How do I pass in an IEntityCache?

Selfconfidence answered 9/2, 2014 at 22:20 Comment(0)
O
3

EntityCache is a singleton with no public construction.

And how do you expect your DI framework to be able to instantiate this class? This cannot possibly work if your class doesn't have a default public constructor or a constructor taking arguments which are already registered in your DI.

You might need to provide the specific instance yourself if the class doesn't have public constructor:

kernel
    .Bind<IEntityCache>()
    .ToMethod(context => ...return your specific instance here...)
    .InSingletonScope();

for example:

kernel
    .Bind<IEntityCache>()
    .ToMethod(context => EntityCache.Instance)
    .InSingletonScope();
Oswell answered 9/2, 2014 at 22:22 Comment(2)
Updated my question a bit.Selfconfidence
Your update doesn't address the problem you are having. Your problem comes from the fact that you are attempting to register a class which cannot be explicitly constructed by Ninject: kernel.Bind<IEntityCache>().To<EntityCache>().InSingletonScope();. The simple reason for that is because the EntityCache implementation, as you already stated, doesn't have a public constructor and Ninject has no way of knowing how to instantiate it. In my answer I have illustrated how you could help it by providing a specific instance you have constructed yourself.Oswell

© 2022 - 2024 — McMap. All rights reserved.