Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
Foundations of Programming - Karl Seguin
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Chapter 4 - Dependency Injection<br />
<br />
<br />
<br />
While I don’t want to spend too much time talking about configuration, it’s important to note that the<br />
XML file must be deployed in the /bin folder <strong>of</strong> your application. You can automate this in VS.NET by<br />
selecting the files, going to the properties and setting the Copy To Ouput Directory attribute to Copy<br />
Always. (There are a variety <strong>of</strong> more advanced configuration options available. If you’re interested in<br />
learning more, I suggest the StructureMap website).<br />
Once configured, we can undo all the changes we made to the Car class to allow constructor injection<br />
(remove the _dataProvider field, and the constructors). To get the correct IDataAccess<br />
implementation, we simply need to ask StructureMap for it, the Save method now looks like:<br />
public class Car<br />
{<br />
private int _id;<br />
}<br />
public void Save()<br />
{<br />
if (!IsValid())<br />
{<br />
//todo: come up with a better exception<br />
throw new InvalidOperationException("The car must be in a valid<br />
state");<br />
}<br />
}<br />
IDataAccess dataAccess = ObjectFactory.GetInstance();<br />
if (_id == 0)<br />
{<br />
_id = dataAccess.Save(this);<br />
}<br />
else<br />
{<br />
dataAccess.Update(this);<br />
}<br />
<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />
31