简体   繁体   English

动态注入绑定

[英]Ninject dynamic binding

I have a UserController which has a reference to UserService where business logic is implemented, and I have several user roles for which I have different behavior in business logic, so I have many 'if statements' in my service. 我有一个UserController,它引用了在其中实现业务逻辑的UserService,并且我有几个用户角色,在这些角色中我在业务逻辑中有不同的行为,因此我的服务中有很多“ if语句”。

Then I decided to make a BaseUserService where I have common behavior for all users and I created a separate service for every role where specific behavior is defined for each role. 然后,我决定创建一个BaseUserService,使所有用户具有相同的行为,并为每个角色创建一个单独的服务,并为每个角色定义特定的行为。

And in controller constructor I check which is user's role and create appropriate service type. 在控制器构造函数中,我检查哪个是用户角色,并创建适当的服务类型。 But I want to know can if I can use this approach using Ninject dependency injection, can I bind user interface to appropriate implementation in controller's constructor at run time? 但是我想知道是否可以通过Ninject依赖注入使用这种方法,我是否可以在运行时将用户界面绑定到控制器构造函数中的适当实现? For instance if user's role is Admin bind User interface to AdminService... Can this be done in Ninject? 例如,如果用户的角色是Admin,则将用户界面绑定到AdminService ...可以在Ninject中完成吗?

What you want to do is pass in an IUserServiceFactory rather than a UserServce inject into Controller Constructor. 您想要做的是传递IUserServiceFactory而不是将UserServce注入Controller构造函数中。 The factory can then be called from Contoller and based on the user role, the factory will return the appropriate implementation. 然后可以从Contoller调用工厂,并根据用户角色,工厂将返回适当的实现。 More information on factory pattern see here . 有关工厂模式的更多信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM