Ninject - Injecting singleton

*爱你&永不变心* 提交于 2019-12-13 18:23:17

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/21665839/ninject-injecting-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!