How to inject an object into a Ninject Module

有些话、适合烂在心里 提交于 2019-12-02 06:12:44

问题


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?

回答1:


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

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