• Ninject 笔记之 对象范围 Kevin


    在很多情况下,同一类型的实例需要在整个应用范围内被使用,通常的做法是使用单例模式:

    1 sealed class Shogun 
    2 {
    3     public static readonly Shogun Instance = new Shogun();
    4     private Shogun() { }
    5     public void RuleWithIronFist() 
    6     {
    7         ...
    8     }
    9 }

    Ninject使单例模式的应用更加简单,不需要更多额外的代码,只需要告诉Ninject绑定单例范围内的类。

    1 kernel.Bind<Shogun>().ToSelf().InSingletonScope();

    在Ninject有很多内置的类型:

    自定义范围

    通过.InScope(Fun<IContext,object> selectScope方法,你可以很容易地定义你自己的范围。

    下面是一个例子用来展示自定义范围的使用:

     1 public class ScopeObject { }
     2 
     3 public static class ProcessingScope
     4 {
     5   public static ScopeObject Current {get; set;}
     6 }
     7 
     8 using Xunit;
     9 public class NinjectCustomScopeExample
    10 {
    11   public class TestService { }
    12 
    13   [Fact]
    14   public static void Test()
    15   {
    16     var kernel = new StandardKernel();
    17     kernel.Bind().ToSelf().InScope( x => ProcessingScope.Current );
    18     
    19     var scopeA = new ScopeObject();
    20     var scopeB = new ScopeObject();
    21    
    22     ProcessingScope.Current = scopeA;
    23     var testA1 = kernel.Get();
    24     var testA2 = kernel.Get();
    25     
    26     Assert.Same( testA2, testA1 );
    27    
    28     ProcessingScope.Current = scopeB;
    29     var testB = kernel.Get();
    30     
    31     Assert.NotSame( testB, testA1 );
    32    
    33     ProcessingScope.Current = scopeA;
    34     var testA3 = kernel.Get();
    35     
    36     Assert.Same( testA3, testA1 );
    37   }
    38 }
  • 相关阅读:
    [JSOI2007][BZOJ1031] 字符加密Cipher|后缀数组
    leetcode Flatten Binary Tree to Linked List
    leetcode Pascal's Triangle
    leetcode Triangle
    leetcode Valid Palindrome
    leetcode Word Ladder
    leetcode Longest Consecutive Sequence
    leetcode Sum Root to Leaf Numbers
    leetcode Clone Graph
    leetcode Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/kfx2007/p/3120941.html
Copyright © 2020-2023  润新知