Javaçéã§ã¯Spring FrameworkãSeasar2ãªã©ãå²ã¨å¸æ°æ¨©ãå¾ã¦ããæãï¼æ®å¿µãªããèªåã®ä»äºã§è¦èãããç¯å²ã§ã¯ä½¿ããã¦ãã¨ããåãèãã¾ãããã»ã»ã»ï¼ã®DIã³ã³ããã§ãããæè¿.NETçéã§ããã¤ã¯ãã½ãããUnityãCodePlexã§æä¾ãããMEFãªãã¦ããæ¡å¼µå¯è½ãªã¢ããªã±ã¼ã·ã§ã³ãä½ãããã®ãã¬ã¼ã ã¯ã¼ã¯ã¨ãã£ã¦å®æ ã¯DIã³ã³ããã®æ©è½ãæãããã¬ã¼ã ã¯ã¼ã¯ã.NET Framework 4ã®æ¨æºã©ã¤ãã©ãªã®ä¸é¨ã¨ãã¦ãªãªã¼ã¹ããããã¦ãã¾ããOSSã§ã¯SpringãSeasarã®.NETã¸ã®ç§»æ¤ãã®ãªãããããã¾ãã
DIã³ã³ããã¨ã¤ã³ã¿ã¼ãã§ã¼ã¹ããã¾ããã¨ä½¿ãã°ã¯ã©ã¹éã®ä¾åé¢ä¿ãåé¢ã§ãã¦åä½ãã¹ããããããã¨ããã¡ãªãããå¾ããã¨ãåºæ¥ã¾ãã
ãã¨ãã°ä»¥ä¸ã®ãããªæãã§ãã
// æ¨æ¶ãããã¤ã³ã¿ã¼ãã§ã¼ã¹ interface IGreeter { string Greet(); } class Greeter : IGreeter { // æ¬æ¥ã¯DBãªããã«ã¢ã¯ã»ã¹ãã¦ãã¼ã¿ã¨ã£ã¦ãããã»ã»ã» public string Greet() { return "ããã«ã¡ã¯"; } } // Greeterã使ç¨ããã¯ã©ã¹ class Client { // Greeterã¯DIã³ã³ããã«ã¤ã³ã¸ã§ã¯ã·ã§ã³ãã¦ããã public IGreeter Greeter { get; set; } // å¼æ°ã§åãåã£ãååã®äººã« public string Execute(string name) { return string.Format("{0}ãã,{1}", name, Greeter.Greet()); } }
DIã³ã³ãããå°å
¥ã§ããªãç°å¢ï¼ã¨ãããç§ã®å¨è¾ºï¼ã§ã¯ãä¸è¨ã®ãããªä¾ã®ã³ã¼ãã¯ä»¥ä¸ã®ããã«æ¸ããã¦ãã¾ãã
// ã¤ã³ã¿ã¼ãã§ã¼ã¹ã¯ãªã public class Greeter { // æ¬æ¥ã¯DBãªããã«ã¢ã¯ã»ã¹ãã¦ãã¼ã¿ã¨ã£ã¦ãããã»ã»ã» public string Greet() { return "ããã«ã¡ã¯"; } } class Client { public string Execute(string name) { var greeter = new Greeter(); return string.Format("{0}ãã,{1}", name, greeter.Greet()); } }
Clientã®ãã¹ãããããã¨ããã¨èã¥ãå¼ã«Greeterã¸ã®æé¤ã§ããªãä¾åé¢ä¿ãã¤ãã¦ããã¨ããæ²ããæãã«ãªã£ã¦ãã¾ããGreeterãDBã¢ã¯ã»ã¹ãããWebãµã¼ãã¹å¼ã³åºããã¦ããç®ããã¦ãããªãæãã§ããããããæãã®ã³ã¼ããæ¸ãã¦ãåä½ãã¹ãã£ã¦ã©ããããã§ããï¼ãã£ã¦è¨ããããã¨ããããã¡ãã£ã¨ã©ãè¨ã£ã¦ããã®ãå°ããã¨ãããã¾ãã
DIã³ã³ããã使ããªãã«ãã¦ããæä½ä»¥ä¸ã®ãããªæ§é ã«ãã¦ã»ããã¨æã£ãããã¾ãã
// ãã¡ãã¨ã¤ã³ã¿ã¼ãã§ã¼ã¹ã使ã£ã¦ä¾åé¢ä¿ã®å¢çç·ãä½ã interface IGreeter { string Greet(); } class Greeter : IGreeter { string Greet() { return "ããã«ã¡ã¯"; } } class Client { // ãã¹ãç¨ã«å·®ãæ¿ãããããã®å£ãä½ã£ã¦ãã private IGreeter greeter; public Client(IGreeter greeter) { this.greeter = greeter; } // æ¬çªã§ä½¿ãæã«ããã©ããããªãããã«ããã©ã«ãã®ã¤ã³ã¹ã¿ã³ã¹ã¯ç¨æãã¦ãã public Client() : this(new Greeter()) {} public string Execute(string name) { return string.Format("{0}ãã,{1}", name, this.greeter.Greet()); } }
ãããã¨ãã°ãåä½ãã¹ãããã«MockGreeterã¿ãããªã¯ã©ã¹ãä½ã£ã¦
var client = new Client(new MockGreeter());
ã¿ããã«åä½ãã¹ãã®ä¸ã§ã¤ã³ã¹ã¿ã³ã¹åã§ããããã«ãªãã¾ããåä½ãã¹ããã«ããæ§é ã§ãã®ãä½ã£ã¦ãã¹ãã©ãããã®ãèããããããåä½ãã¹ãã®ãããããèãã¦è¨è¨ãããã¨ããã®ã¯éè¦ãªãã¨ã ã¨æãä»æ¥ãã®é ã§ããã