How to inject an object into a Ninject Module



  • I am using Ninject for DI. I have Ninject Modules that bind some services to the Kernel and use binded object in other modules as a service. To clear the situation let's see some lines of code: This is my security module. It provides a service named PermissionManagerContainer.

    public class SecurityModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IPermissionManagerContainer>().To<PermissionManagerContainer>().InSingletonScope();
        }
    }
    
    

    At the other hand I have a FormServices module that should add an item to the injected PermissionManagerContainer. I think the code must be something like this:

    public class FormServicesModule : NinjectModule
    {
        [Ninject.Inject]
        private IPermissionManagerContainer permissionManagerContainer { get; set; }
    
        public override void Load()
        {
            permissionManagerContainer.RegisterManager(formServicesPermissionManager);
        }
    }
    
    

    So in a page named ManagePermissions.aspx again I inject the PermissionManagerContainer and create user interface for Permission Managers of all modules. For example, I need to secure Forms in my FormServices module and define permissions for every form in that service.

    But I think there are no guarantee for binding PermissionManagerContainer before injecting it in another module!

    Actually, I have my own solution for this problem. I can write an abstract class named MyModule which is sub classed from NinjectModule and write an abstract method called InitializeModule. and call RegisterManager in that method. Then call the InitializeModule for every module loaded, after loading all modules in kernel.

    But my questions are:

    1. Does Ninject has this feature internally or not?
    2. It is probable to Ninject manage this case internally and I could call the RegisterManager in the load method. Is it true?

    Remo Gloor

    You are misunderstanding the purpose of modules. They are there to configure Ninject. They themselves shouldn't have any dependencies at all. The RegisterManager belongs somewhere in a service or startup action of your application. Or probably you have to change the way the permission manager works so that it takes an enumerable of all configured managers instead of registering them. But it's nearly impossible to tell what is best from the question -- just that you are abusing modules for something they are not intended for.

    来自:https://stackoverflow.com/questions/8022062/how-to-inject-an-object-into-a-ninject-module


Log in to reply
 

最新帖子

推荐阅读