Binding singleton to multiple services in Ninject

前端 未结 3 1630
情深已故
情深已故 2020-12-03 12:18

I have a problem which seems very similar to the one described in http://markmail.org/message/6rlrzkgyx3pspmnf which is about the singleton actually creating more than a sin

3条回答
  •  暖寄归人
    2020-12-03 13:02

    We used Ruben's method in our project, but found that it wasn't intuitive why you were going back to the Kernel in your binding. I created an extension method and helper class (below) so you can do this:

    kernel.Bind().ToExisting().Singleton();
    

    That seemed to express the intent more clearly to me.

    public static class DIExtensions
    {
        public static ToExistingSingletonSyntax ToExisting(this IBindingToSyntax binding)
        {
            return new ToExistingSingletonSyntax(binding);
        }
    }
    
    // Had to create this intermediate class because we have two type parameters -- the interface and the implementation,
    // but we want the compiler to infer the interface type and we supply the implementation type.  C# can't do that.
    public class ToExistingSingletonSyntax
    {
        internal ToExistingSingletonSyntax(IBindingToSyntax binding)
        {
            _binding = binding;
        }
    
        public IBindingNamedWithOrOnSyntax Singleton() where TImplementation : T
        {
            return _binding.ToMethod(ctx => ctx.Kernel.Get()).InSingletonScope();
        }
    
    
        private IBindingToSyntax _binding;
    }
    

提交回复
热议问题