Lazy Loading with Ninject

后端 未结 2 515
北海茫月
北海茫月 2020-12-09 05:45

I\'m evaluating ninject2 but can\'t seem to figure out how to do lazy loading other than through the kernel.

From what I can see that kind of defeats the purpose of

2条回答
  •  情深已故
    2020-12-09 06:17

    There is a simpler way to do this:

    public class Module : NinjectModule
    {
        public override void Load()
        {
            Bind(typeof(Lazy<>)).ToMethod(ctx => 
                    GetType()
                        .GetMethod("GetLazyProvider", BindingFlags.Instance | BindingFlags.NonPublic)
                        .MakeGenericMethod(ctx.GenericArguments[0])
                        .Invoke(this, new object[] { ctx.Kernel }));
        }
    
        protected Lazy GetLazyProvider(IKernel kernel)
        {
            return new Lazy(() => kernel.Get());
        }
    }
    

提交回复
热议问题