简体   繁体   中英

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.

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.

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? For instance if user's role is Admin bind User interface to AdminService... Can this be done in Ninject?

What you want to do is pass in an IUserServiceFactory rather than a UserServce inject into Controller Constructor. The factory can then be called from Contoller and based on the user role, the factory will return the appropriate implementation. More information on factory pattern see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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