Ninject: Shared DI/IoC container

江枫思渺然 提交于 2019-12-24 07:32:10

问题


I want to share the container across various layers in my application. I started creating a static class which initialises the container and register types in the container.

public class GeneralDIModule : NinjectModule
{
    public override void Load()
    {
        Bind<IDataBroker>().To<DataBroker>().InSingletonScope();
    }
}

public abstract class IoC
{
    private static IKernel _container;

    public static void Initialize()
    {
        _container = new StandardKernel(new GeneralDIModule(), new ViewModelDIModule());
    }

    public static T Get<T>()
    {
        return _container.Get<T>();
    }
}

I noticed there is a Resolve method as well. What is the difference between Resolve and Get?

In my unit tests I don’t always want every registered type in my container. Is there a way of initializing an empty container and then register types I need. I’ll be mocking types as well in unit test so I’ll have to register them as well.

There is an Inject method, but it says lifecycle of instance is not managed?

Could someone please set me in right way?

How can I register, unregister objects and reset the container.


回答1:


Ninject by default binds components in a transient lifestyle and Ninject does not track transient instances. The Resolve is used internally and shouldn't be used by your code unless you really know what you are doing. If you want to mock your container, use the ninject.moq extension on github. The inject method you are referring to is for instances that you have created yourself. Use the Get and TryGet methods.



来源:https://stackoverflow.com/questions/2862698/ninject-shared-di-ioc-container

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