{"id":450,"date":"2016-02-24T14:51:04","date_gmt":"2016-02-24T14:51:04","guid":{"rendered":"https:\/\/blogs.mathworks.com\/developer\/?p=450"},"modified":"2016-02-26T13:38:41","modified_gmt":"2016-02-26T13:38:41","slug":"dependency-injection","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/developer\/2016\/02\/24\/dependency-injection\/","title":{"rendered":"Dependency, Injected"},"content":{"rendered":"<div class=\"content\"><p>Now that we have <a href=\"https:\/\/blogs.mathworks.com\/developer\/2016\/02\/16\/inversion-of-control\/\">conquered inversion of control<\/a>, we can explore a common application of the technique, <i>dependency injection<\/i>. Dependency injection utilizes the inversion of control to, with the aid of a dependency injection framework, construct an application through configuration rather than code. This allows your application to be distributed to perhaps many different customers with many different needs, and rather than changing the foundational code to suit these needs, you can provide for them a configuration file as well as the specific implementation of the code they need. However, the core infrastructure can be shared among many different and varied clients because the core infrastructure does not directly depend on any of the concrete implementations of the code needed for each customer.<\/p><p>In other words, using our spell checking example, you can separate the core spell checking engine and interface along with the locale specific dictionaries and distribute them separately. We showed last post that this can be done using our inversion of control technique, but it requires your end user to build up the application. If you gave a user of your software the spellchecker and the <tt>MexicanSpanishDictionary<\/tt>, they still would need to create it by doing something like:<\/p><pre class=\"codeinput\">checker = spellcheck(MexicanSpanishDictionary)\r\n<\/pre><pre class=\"codeoutput\">\r\nchecker = \r\n\r\n  spellcheck with no properties.\r\n\r\n<\/pre><p>This seems easy enough, but in real world applications you have more than one dependency and it is likely not this easy to construct your entire application's object graph. However, using dependency injection you can create your application and distribute it with different behaviors, in our case with a specific configuration for each locale we'd like to support.<\/p><p>If you are intrigued by this possibility, as it turns out you are in luck because there is a dependency injection framework <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/52394-matlab-dependency-injection\">on the file exchange<\/a> to help out with this.<\/p><p>But first, did you do your homework? You may remember <a href=\"https:\/\/blogs.mathworks.com\/developer\/2016\/02\/16\/inversion-of-control\/\">last post<\/a> I suggested continuing the inversion of control technique on the spellchecker but applying the technique on the engine as well as the dictionary. Anyone do it? If not go read that post and try your hand at it because I am about to show you the solution (<b>SPOILER ALERT<\/b>) so we can extend this concept here. I'd like to show how dependency injection can be used across at least a couple layers so that going through that exercise will be helpful.<\/p><p>Alright the key here is that even though the <tt>spellcheck<\/tt> constructor was handling both the <tt>Dictionary<\/tt> and the Engine (Jazzy), for our purposes it really only needed the engine. The engine is what needed the <tt>Dictionary<\/tt>, and in fact it is conceivable that there may be some engines that don't rely on the same <tt>Dictionary<\/tt> interface at all. What did need the <tt>Dictionary<\/tt> was the Jazzy engine. So it follows that instead of the <tt>spellcheck<\/tt> class asking for the <tt>Dictionary<\/tt> in its constructor, the spellcheck class can simply ask for the engine. To do this we need to define an interface for what the engine needs to provide:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> SpellCheckEngine &lt; handle\r\n    \r\n    <span class=\"keyword\">methods<\/span>(Abstract)\r\n        checkSpelling(engine, inputStr);\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n<\/pre><p>Then we can operate on that interface directly in the spellcheck code:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> spellcheck\r\n    \r\n    <span class=\"keyword\">properties<\/span>(GetAccess=private, SetAccess=immutable)\r\n        Engine;\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> checker = spellcheck(engine)\r\n            <span class=\"comment\">% Hold onto our spellchecking engine<\/span>\r\n            checker.Engine = engine;\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n<span class=\"comment\">        %% CHECK Method to check an input string<\/span>\r\n        <span class=\"keyword\">function<\/span> check(checker, inputStr)\r\n            checker.Engine.checkSpelling(inputStr);\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    \r\n<span class=\"keyword\">end<\/span> \r\n\r\n<\/pre><p>Finally, let's add our specific Jazzy engine and see how we can establish the same behavior as last post:<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> JazzySpellCheckEngine &lt; SpellCheckEngine\r\n    \r\n    <span class=\"keyword\">properties<\/span>(GetAccess=private, SetAccess=immutable)\r\n        Jazzy\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> engine = JazzySpellCheckEngine(dictionary)\r\n            engine.Jazzy = com.mathworks.spellcheck.SpellCheck();\r\n            engine.Jazzy.setDictionary(dictionary.DictionaryFile);\r\n            engine.Jazzy.verbose = true;\r\n        <span class=\"keyword\">end<\/span>\r\n        <span class=\"keyword\">function<\/span> checkSpelling(engine, inputStr)\r\n            engine.Jazzy.checkSpelling(inputStr);\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n<\/pre><pre class=\"codeinput\">s = spellcheck(JazzySpellCheckEngine(AmericanEnglishDictionary));\r\ns.check(<span class=\"string\">'&iquest;Hablas MATLAB?'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">Input : Hablas\r\n\tSuggestion: tablas\r\n<\/pre><p>Great! We are in business and each class looks very clean with a single responsibility. In fact, they are not even responsible for constructing their own dependencies! This is really an application of the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Single_responsibility_principle\">Single Responsibility Principle<\/a>. Something <i>else<\/i> has the responsibility of wiring all these objects together, not the objects themselves in their constructors.<\/p><p><b>Add some DI<\/b><\/p><p>OK, now the person responsible for creating your full object connections <b>should not be your end user<\/b>. You can see with even two collaborators that it is starting to get verbose.<\/p><pre class=\"codeinput\">s = spellcheck(JazzySpellCheckEngine(AmericanEnglishDictionary))\r\n<\/pre><pre class=\"codeoutput\">\r\ns = \r\n\r\n  spellcheck with no properties.\r\n\r\n<\/pre><p>Instead let's make it a configuration. The first step that is needed in order to leverage this dependency injection framework is to opt into allowing the framework to construct instances of your objects by deriving from the DI framework's <tt>mdepin.Bean<\/tt> interface. Note, I have placed the version of the spellcheck code which uses dependency injection <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/matlab_oop\/scoping-classes-with-packages.html\">into a package<\/a> called <tt>di<\/tt> to keep the dependency injection version seperate from our first spellchecker. When we derive from the <tt>Bean<\/tt> interface we need to also pass the configuration passed into the constructor up the class hierarchy to the <tt>Bean<\/tt> superclass. For our classes this looks like the following (placed into a <b><tt>+di<\/tt><\/b> folder to place it into the package):<\/p><pre class=\"language-matlab\">\r\n<span class=\"keyword\">classdef<\/span> spellcheck &lt; mdepin.Bean\r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        Engine;\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> checker = spellcheck(config)\r\n            checker = checker@mdepin.Bean(config);\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n<span class=\"comment\">        %% CHECK Method to check an input string<\/span>\r\n        <span class=\"keyword\">function<\/span> check(checker, inputStr)\r\n            checker.Engine.checkSpelling(inputStr);\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    \r\n<span class=\"keyword\">end<\/span> \r\n\r\n\r\n\r\n<span class=\"keyword\">classdef<\/span> SpellCheckEngine &lt; mdepin.Bean\r\n    \r\n    <span class=\"keyword\">methods<\/span>(Abstract)\r\n        checkSpelling(engine, inputStr);\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> engine = SpellCheckEngine(config)\r\n            engine = engine@mdepin.Bean(config);\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n\r\n\r\n<span class=\"keyword\">classdef<\/span> JazzySpellCheckEngine &lt; di.SpellCheckEngine\r\n\r\n    <span class=\"keyword\">properties<\/span>\r\n        Dictionary\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">properties<\/span>(GetAccess=private, SetAccess=immutable)\r\n        Jazzy\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> engine = JazzySpellCheckEngine(config)\r\n            engine = engine@di.SpellCheckEngine(config);\r\n            engine.Jazzy = com.mathworks.spellcheck.SpellCheck();\r\n            engine.Jazzy.setDictionary(engine.Dictionary.DictionaryFile);\r\n            engine.Jazzy.verbose = true;\r\n        <span class=\"keyword\">end<\/span>\r\n        <span class=\"keyword\">function<\/span> checkSpelling(engine, inputStr)\r\n            engine.Jazzy.checkSpelling(inputStr);\r\n        <span class=\"keyword\">end<\/span>\r\n        \r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n\r\n\r\n<span class=\"keyword\">classdef<\/span> Dictionary &lt; matlab.mixin.Heterogeneous &amp; mdepin.Bean\r\n    \r\n    <span class=\"keyword\">properties<\/span>(Abstract)\r\n        DictionaryFile\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> dictionary = Dictionary(config)\r\n            dictionary = dictionary@mdepin.Bean(config);\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n\r\n\r\n\r\n<span class=\"keyword\">classdef<\/span> AmericanEnglishDictionary &lt; di.Dictionary\r\n    \r\n    <span class=\"keyword\">properties<\/span>\r\n        DictionaryFile = <span class=\"string\">'en_USx.dic'<\/span>;\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n    <span class=\"keyword\">methods<\/span>\r\n        <span class=\"keyword\">function<\/span> dictionary = AmericanEnglishDictionary(config)\r\n            dictionary = dictionary@di.Dictionary(config);\r\n        <span class=\"keyword\">end<\/span>\r\n    <span class=\"keyword\">end<\/span>\r\n    \r\n<span class=\"keyword\">end<\/span>\r\n    \r\n\r\n<\/pre><p>The only differences here are the superclass lists to derive from <tt>mdepin.Bean<\/tt> and the changes to the constructors to both accept the configuration and forward that configuration to the superclasses.<\/p><p>However, now we can let the configuration create our object graph for us! First we create a structure for this context. Note that this configuration is specified as a structure, which feels a bit like code rather than configuration, but that is because the framework supports this context as a struct out of the box. This can very easily be extended to create a context class from a more classically declarative form like JSON or XML. You just need to create your own subclass of mdepin.Context in order to produce these forms of configuration. For our part, the structure version of these declarations will do just fine:<\/p><pre class=\"codeinput\"><span class=\"comment\">% Define the spellcheck class and give it a label \"spellchecker\"<\/span>\r\nctx.spellchecker.class = <span class=\"string\">'di.spellcheck'<\/span>;\r\n<span class=\"comment\">% Assign a label in the configuration which defines the required engine<\/span>\r\nctx.spellchecker.Engine = <span class=\"string\">'spell_check_engine'<\/span>;\r\n\r\n<span class=\"comment\">% Link the JazzySpellCheckEngine to our engine label<\/span>\r\nctx.spell_check_engine.class = <span class=\"string\">'di.JazzySpellCheckEngine'<\/span>;\r\n<span class=\"comment\">% Assign a label in the configuration which defines the required dictionary<\/span>\r\nctx.spell_check_engine.Dictionary = <span class=\"string\">'american_english_dictionary'<\/span>;\r\n\r\n<span class=\"comment\">% Link the AmericanEnglishDictionary to our dictionary label<\/span>\r\nctx.american_english_dictionary.class = <span class=\"string\">'di.AmericanEnglishDictionary'<\/span>;\r\n<\/pre><p>With this structure based configuration the framework can then construct our full object graph for us.<\/p><pre class=\"codeinput\">s = mdepin.createApplication(ctx, <span class=\"string\">'spellchecker'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">\r\ns = \r\n\r\n  spellcheck with properties:\r\n\r\n    Engine: [1x1 di.JazzySpellCheckEngine]\r\n\r\n<\/pre><p>Does it work? If so it should find a typo here because we are using the English dictionary.<\/p><pre class=\"codeinput\">s.check(<span class=\"string\">'&iquest;Hablas MATLAB?'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">Input : Hablas\r\n\tSuggestion: tablas\r\n<\/pre><p>&iexcl;Absolutamente!<\/p><p>There we have it, we have now separated out our construction logic, and using the dependency injection framework have made it such that our construction logic can be configuration rather than code. This allows flexibility in distribution of our MATLAB software packages because different clients can use different configurations.<\/p><p>Should everything use dependency injection? Not necessarily. It has some definite upsides to it, but it does require an additional dependency on a DI framework, and it can affect the way the software is written. For example, in this example we needed to modify our classes to derive from something outside our domain model (the <tt>Bean<\/tt>) and our constructor signatures are affected by the use of the framework. Using manual constructor injection is definitely a valid choice, it just requires that other collaborators in your software (factories perhaps) have the responsibility to construct the object graph. If you don't mind the framework dependency and you'd like to delegate that responsibility to a tool then a DI framework can work quite nicely for you.<\/p><p>Another related pattern is a Service Locator, which also has its own pros and cons, but supports similar use cases with a more dynamic resolution of needed dependencies. Many view Dependency Injection as a competing pattern to Service Locators. I tend to view them as complimentary. I'd like to cover a post on Service Locators in MATLAB in the future, but for now let's all take a break from the topic for a bit. That's code-speak for <i>\"We have some cool posts in the pipeline on some different topics.\"<\/i> Remember that R2016a comes out in early March! <b>hint<\/b> <b>grin<\/b><\/p><p>In the meantime have you ever wanted a DI framework in MATLAB? This file exchange example is relatively new so definitely give it a go. Can you see a dependency injection framework helping with your production code?<\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_1e660f6e06c64934bf7be2bac820dace() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='1e660f6e06c64934bf7be2bac820dace ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 1e660f6e06c64934bf7be2bac820dace';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2016 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_1e660f6e06c64934bf7be2bac820dace()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2015b<br><\/p><\/div><!--\r\n1e660f6e06c64934bf7be2bac820dace ##### SOURCE BEGIN #####\r\n%%\r\n% Now that we have\r\n% <https:\/\/blogs.mathworks.com\/developer\/2016\/02\/16\/inversion-of-control\/\r\n% conquered inversion of control>, we can explore a common application of\r\n% the technique, _dependency injection_. Dependency injection utilizes the\r\n% inversion of control to, with the aid of a dependency injection\r\n% framework, construct an application through configuration rather than\r\n% code. This allows your application to be distributed to perhaps many\r\n% different customers with many different needs, and rather than changing\r\n% the foundational code to suit these needs, you can provide for them a\r\n% configuration file as well as the specific implementation of the code\r\n% they need. However, the core infrastructure can be shared among many\r\n% different and varied clients because the core infrastructure does not\r\n% directly depend on any of the concrete implementations of the code needed\r\n% for each customer.\r\n%\r\n% In other words, using our spell checking example, you can separate the\r\n% core spell checking engine and interface along with the locale specific\r\n% dictionaries and distribute them separately. We showed last post that\r\n% this can be done using our inversion of control technique, but it\r\n% requires your end user to build up the application. If you gave a user of\r\n% your software the spellchecker and the |MexicanSpanishDictionary|, they\r\n% still would need to create it by doing something like:\r\nchecker = spellcheck(MexicanSpanishDictionary)\r\n\r\n%% \r\n% This seems easy enough, but in real world applications you have more than\r\n% one dependency and it is likely not this easy to construct your entire\r\n% application's object graph. However, using dependency injection you can\r\n% create your application and distribute it with different behaviors, in\r\n% our case with a specific configuration for each locale we'd like to support.\r\n%\r\n% If you are intrigued by this possibility, as it turns out you are in luck\r\n% because there is a dependency injection framework\r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/52394-matlab-dependency-injection\r\n% on the file exchange> to help out with this.\r\n%\r\n% But first, did you do your homework? You may remember\r\n% <https:\/\/blogs.mathworks.com\/developer\/2016\/02\/16\/inversion-of-control\/\r\n% last post> I suggested continuing the inversion of control technique on\r\n% the spellchecker but applying the technique on the engine as well as the\r\n% dictionary. Anyone do it? If not go read that post and try your hand at\r\n% it because I am about to show you the solution (*SPOILER ALERT*) so we\r\n% can extend this concept here. I'd like to show how dependency injection\r\n% can be used across at least a couple layers so that going through that\r\n% exercise will be helpful.\r\n%\r\n% Alright the key here is that even though the |spellcheck| constructor was\r\n% handling both the |Dictionary| and the Engine (Jazzy), for our purposes\r\n% it really only needed the engine. The engine is what needed the\r\n% |Dictionary|, and in fact it is conceivable that there may be some\r\n% engines that don't rely on the same |Dictionary| interface at all. What\r\n% did need the |Dictionary| was the Jazzy engine. So it follows that instead\r\n% of the |spellcheck| class asking for the |Dictionary| in its constructor,\r\n% the spellcheck class can simply ask for the engine. To do this we need to\r\n% define an interface for what the engine needs to provide:\r\n%\r\n% <include>SpellCheckEngine.m<\/include>\r\n%\r\n% Then we can operate on that interface directly in the spellcheck code:\r\n%\r\n% <include>spellcheck.m<\/include>\r\n%\r\n% Finally, let's add our specific Jazzy engine and see how we can establish\r\n% the same behavior as last post:\r\n%\r\n% <include>JazzySpellCheckEngine.m<\/include>\r\n%\r\ns = spellcheck(JazzySpellCheckEngine(AmericanEnglishDictionary));\r\ns.check('\u00c2\u00bfHablas MATLAB?')\r\n\r\n%%\r\n% Great! We are in business and each class looks very clean with a single\r\n% responsibility. In fact, they are not even responsible for constructing\r\n% their own dependencies! This is really an application of the\r\n% <https:\/\/en.wikipedia.org\/wiki\/Single_responsibility_principle Single\r\n% Responsibility Principle>. Something _else_ has the responsibility of\r\n% wiring all these objects together, not the objects themselves in their\r\n% constructors.\r\n%\r\n% *Add some DI*\r\n%\r\n% OK, now the person responsible for creating your full object connections\r\n% *should not be your end user*. You can see with even two collaborators\r\n% that it is starting to get verbose.\r\ns = spellcheck(JazzySpellCheckEngine(AmericanEnglishDictionary))\r\n\r\n%%\r\n% Instead let's make it a configuration. The first step that is needed in\r\n% order to leverage this dependency injection framework is to opt into\r\n% allowing the framework to construct instances of your objects by deriving\r\n% from the DI framework's |mdepin.Bean| interface. Note, I have placed the\r\n% version of the spellcheck code which uses dependency injection\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/matlab_oop\/scoping-classes-with-packages.html\r\n% into a package> called |di| to keep the dependency injection version\r\n% seperate from our first spellchecker. When we derive from the |Bean|\r\n% interface we need to also pass the configuration passed into the\r\n% constructor up the class hierarchy to the |Bean| superclass. For our\r\n% classes this looks like the following (placed into a *|+di|* folder to\r\n% place it into the package):\r\n%\r\n% <include>+di\/spellcheck.m<\/include>\r\n%\r\n% <include>+di\/SpellCheckEngine.m<\/include>\r\n%\r\n% <include>+di\/JazzySpellCheckEngine.m<\/include>\r\n%\r\n% <include>+di\/Dictionary.m<\/include>\r\n%\r\n% <include>+di\/AmericanEnglishDictionary.m<\/include>\r\n%\r\n% The only differences here are the superclass lists to derive from\r\n% |mdepin.Bean| and the changes to the constructors to both accept the\r\n% configuration and forward that configuration to the superclasses.\r\n%\r\n% However, now we can let the configuration create our object graph for us!\r\n% First we create a structure for this context. Note that this\r\n% configuration is specified as a structure, which feels a bit like code\r\n% rather than configuration, but that is because the framework supports\r\n% this context as a struct out of the box. This can very easily be extended\r\n% to create a context class from a more classically declarative form like\r\n% JSON or XML. You just need to create your own subclass of mdepin.Context\r\n% in order to produce these forms of configuration. For our part, the\r\n% structure version of these declarations will do just fine:\r\n\r\n% Define the spellcheck class and give it a label \"spellchecker\"\r\nctx.spellchecker.class = 'di.spellcheck';\r\n% Assign a label in the configuration which defines the required engine\r\nctx.spellchecker.Engine = 'spell_check_engine'; \r\n\r\n% Link the JazzySpellCheckEngine to our engine label\r\nctx.spell_check_engine.class = 'di.JazzySpellCheckEngine';\r\n% Assign a label in the configuration which defines the required dictionary\r\nctx.spell_check_engine.Dictionary = 'american_english_dictionary';\r\n\r\n% Link the AmericanEnglishDictionary to our dictionary label\r\nctx.american_english_dictionary.class = 'di.AmericanEnglishDictionary';\r\n\r\n\r\n%%\r\n% With this structure based configuration the framework can then construct\r\n% our full object graph for us.\r\ns = mdepin.createApplication(ctx, 'spellchecker')\r\n\r\n%%\r\n% Does it work? If so it should find a typo here because we are using the\r\n% English dictionary.\r\ns.check('\u00c2\u00bfHablas MATLAB?')\r\n\r\n%%\r\n% \u00c2\u00a1Absolutamente!\r\n%\r\n% There we have it, we have now separated out our construction logic, and\r\n% using the dependency injection framework have made it such that our\r\n% construction logic can be configuration rather than code. This allows\r\n% flexibility in distribution of our MATLAB software packages because\r\n% different clients can use different configurations.\r\n%\r\n% Should everything use dependency injection? Not necessarily. It has some\r\n% definite upsides to it, but it does require an additional dependency on a\r\n% DI framework, and it can affect the way the software is written. For\r\n% example, in this example we needed to modify our classes to derive from\r\n% something outside our domain model (the |Bean|) and our constructor\r\n% signatures are affected by the use of the framework. Using manual\r\n% constructor injection is definitely a valid choice, it just requires that\r\n% other collaborators in your software (factories perhaps) have the\r\n% responsibility to construct the object graph. If you don't mind the\r\n% framework dependency and you'd like to delegate that responsibility to a\r\n% tool then a DI framework can work quite nicely for you.\r\n%\r\n% Another related pattern is a Service Locator, which also has its own pros\r\n% and cons, but supports similar use cases with a more dynamic resolution\r\n% of needed dependencies. Many view Dependency Injection as a competing\r\n% pattern to Service Locators. I tend to view them as complimentary. I'd\r\n% like to cover a post on Service Locators in MATLAB in the future, but for\r\n% now let's all take a break from the topic for a bit. That's code-speak\r\n% for _\"We have some cool posts in the pipeline on some different topics.\"_\r\n% Remember that R2016a comes out in early March! *hint* *grin*\r\n%\r\n% In the meantime have you ever wanted a DI framework in MATLAB? This file\r\n% exchange example is relatively new so definitely give it a go. Can you\r\n% see a dependency injection framework helping with your production code?\r\n\r\n\r\n##### SOURCE END ##### 1e660f6e06c64934bf7be2bac820dace\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img src=\"https:\/\/blogs.mathworks.com\/developer\/files\/2016DependencyInjectionConfig.png\" class=\"img-responsive attachment-post-thumbnail size-post-thumbnail wp-post-image\" alt=\"\" decoding=\"async\" loading=\"lazy\" \/><\/div><p>Now that we have conquered inversion of control, we can explore a common application of the technique, dependency injection. Dependency injection utilizes the inversion of control to, with the aid of... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/developer\/2016\/02\/24\/dependency-injection\/\">read more >><\/a><\/p>","protected":false},"author":90,"featured_media":459,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[12,5],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/450"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/users\/90"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/comments?post=450"}],"version-history":[{"count":6,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/450\/revisions"}],"predecessor-version":[{"id":460,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/posts\/450\/revisions\/460"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/media\/459"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/media?parent=450"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/categories?post=450"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/developer\/wp-json\/wp\/v2\/tags?post=450"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}