How to tell Ninject to inject the same instance for nested constructors?

て烟熏妆下的殇ゞ 提交于 2019-12-12 11:31:53

问题


I have a Windows Service application, where I would like to use Ninject for my service classes. There are some service classes which use other, let's say "lower level", or more generic service classes. Each service usually needs a repository for data access.

So for example I have an IRepository interface, an IServices1 and an IServices2 interface. There are Services1 and Services2 implementations of the latter two, both having a constructor parameter of type IRepository. Now assume that implementation of Services1 would like to use some methods of IServices2 interface, so I add another constructor parameter to Services1 with type IServices2. Now when I manually instantiate the Services1 class, I would do tings like:

var repo = new MyRepository(); // implementing IRepository
var service1 = new Services1(repo, new Services2(repo));

This way I can ensure that both services are going to work with the same repository (which is a basic requirement for me).

How can I use Ninject for this scneario to prepare an IServices1 instance for me with the proper IRepository injection? Or do I have any major design mistake with this approach?

I'm not on MVC platform, so I don't have the request scope here, which I think would do the task if it were MVC.


回答1:


Have a look at the NamedScope extension. There are examples for this scenario.

https://github.com/ninject/ninject.extensions.namedscope/wiki



来源:https://stackoverflow.com/questions/15922739/how-to-tell-ninject-to-inject-the-same-instance-for-nested-constructors

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