<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[thecodemonks - Medium]]></title>
        <description><![CDATA[Technical and philosophical discussions on board of programming concepts, software development, architectures, tips, joint problems and solutions. - Medium]]></description>
        <link>https://medium.com/thecodemonks?source=rss----aebce2317dbf---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>thecodemonks - Medium</title>
            <link>https://medium.com/thecodemonks?source=rss----aebce2317dbf---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 21:26:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/thecodemonks" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cautions applying Repository and Unit of Work Patterns with Dependency Injection in Domain-Driven…]]></title>
            <link>https://medium.com/thecodemonks/cautions-applying-repository-and-unit-of-work-patterns-with-dependency-injection-in-domain-driven-52fbe05bf9a5?source=rss----aebce2317dbf---4</link>
            <guid isPermaLink="false">https://medium.com/p/52fbe05bf9a5</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[unitofwork-pattern]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <dc:creator><![CDATA[Icaro Torres]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 16:26:25 GMT</pubDate>
            <atom:updated>2024-01-02T21:06:59.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cautions applying Repository and Unit of Work Patterns with Dependency Injection in Domain-Driven Design!</h3><h4>And what they are supposed to do…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrROlI4xsi_p07akG8LwfA.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@divinetechygirl?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Christina Morillo</strong></a> from <a href="https://www.pexels.com/photo/white-dry-erase-board-with-red-diagram-1181311/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong>Pexels</strong></a></figcaption></figure><h3>Introduction</h3><p>Software Engineering is a vast knowledge area, always moving forward. However, developing good software is an arduous task until now. Furthermore, to achieve software of quality easier, engineers keep investigating common problems to design patterns solving then. As results, we have many known Design Patterns and Software Development Principles to make developers focus as much as possible on the client’s needs.</p><p>On the other hand, these principles and patterns are not well comprehended and applied by developers at the very beginning of their career, and even experienced ones can sometimes misuse or wrongly pick up some of those patterns.</p><p>This article argues three popular patterns often present in .Net solutions with Domain-Driven Design which I’ve seen misunderstood. Showing also, what these patterns solve, how wrong they happened, and how to fix something for the implementation to make sense.</p><h3>SOLID Principles</h3><p>You can read this <a href="https://itnext.io/solid-principles-explanation-and-examples-715b975dcad4">Post</a> by <a href="https://medium.com/u/581a74170cf5">Simon LH</a> explaining way more about SOLID with code examples.</p><p>It is an acronym for five important design principles introduced by Robert C. Martin (Uncle Bob) and updated later by Michael Feathers, listed below with definitions from <a href="https://medium.com/u/581a74170cf5">Simon LH</a>’s post:</p><h4>S — Single responsibility Principle</h4><blockquote>“In programming, the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> states that every module or class should have responsibility for a single part of the functionality provided by the software.”</blockquote><h4>O — Open-Closed Principle</h4><blockquote>“In programming, the <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">open/closed principle</a> states that software entities (classes, modules, functions) should be open for extensions, but closed for modification.”</blockquote><h4>L — Liskov Substitution Principle</h4><blockquote>“In programming, the <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov substitution principle</a> states that if <strong><em>S</em></strong> is a subtype of <strong><em>T</em></strong>, then objects of type <strong><em>T</em></strong> may be replaced (or substituted) with objects of type <strong><em>S</em></strong>.</blockquote><blockquote>We can formulate this mathematically as</blockquote><blockquote><em>Let </em><strong><em>ϕ(x)</em></strong><em> be a property provable about objects </em><strong><em>x</em></strong><em> of type </em><strong><em>T</em></strong><em>.</em></blockquote><blockquote><em>Then </em><strong><em>ϕ(y)</em></strong><em> should be valid for objects </em><strong><em>y</em></strong><em> of type </em><strong><em>S</em></strong><em>, where </em><strong><em>S</em></strong><em> is a subtype of </em><strong><em>T</em></strong><em>.</em></blockquote><blockquote>More generally, it states that objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”</blockquote><h4>I — Interface Segregation Principle</h4><blockquote>“In programming, the <a href="https://en.wikipedia.org/wiki/Interface_segregation_principle">interface segregation principle</a> states not to force a client to depend on methods it does not use.</blockquote><blockquote>Put more simply: Do not add additional functionality to an existing interface by adding new methods.</blockquote><blockquote>Instead, create a new interface and let your class implement multiple interfaces if needed.”</blockquote><h4>D — Dependency Inversion Principle (Dependency injection)</h4><blockquote>“In programming, the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">dependency inversion principle</a> is a way to decouple software modules.</blockquote><blockquote>This principle states that</blockquote><blockquote>* High-level modules should not depend on low-level modules. Both should depend on abstractions.</blockquote><blockquote>* Abstractions should not depend on details. Details should depend on abstractions.</blockquote><blockquote>To comply with this principle, we need to use a design pattern known as a <em>dependency inversion pattern</em>, most often solved by using <a href="https://en.wikipedia.org/wiki/Dependency_injection"><em>dependency injection</em></a><em>.”</em></blockquote><p>These principles save us from lots of headaches in software development and are always suitable for fulfilling as much as possible of then in Object-Oriented Programming paradigm.</p><p>For this article, we only focus on the last one.</p><h3>Dependency Injection Pattern</h3><p>If you are adept to <strong>TDD</strong> (Test-Driven Development), or as long as you may want to make your code testable, you’ve heard about this pattern.</p><h4>Concept and benefits</h4><p>It consists of developing concrete implementations around contract signatures of interfaces, abstracting the real features, allowing alternative behaviours depending on what was injected and making code replaceable by testing mocks.</p><p>It provides testability, re-usability and decouples feature’s code from where uses It.</p><h4>What can a lousy Dependency Injection cause?</h4><p>Making a wrong configuration of your dependency injection container can cause:</p><ul><li>Wrongly disposed structures;</li><li>Heavy load of unused instances;</li><li>Miss-injected behaviours;</li><li>Unnecessary complexity;</li><li>Infinity loops in the container initialization (if there are any cycling dependencies between injected types).</li></ul><h3>Repository Pattern</h3><p>This pattern shows off with Object-relational mapping technologies (ORM) and data access layer abstractions over databases. It consists of managing data sources (mostly database tables or contents from web services resources) as in-memory collections of domain objects and to perform operations over It in a more straightforward way than mounting SQL queries or writing HTTP requests by hand whenever data was needed.</p><h4>What to expect?</h4><p>What we expect from a repository following this pattern is CRUD operations of the referred abstracted entity source and maybe a variety of specific methods (like filtering and joining a subject table with Its relationships) to bring ease usage of this repository.</p><p>A repository of this pattern works as a gatherer of data about a domain object and should only make changes in the referred source and data related to It, like a table and tables in relationships.</p><p>It’s preferred to reuse your base repository logic through <strong>composition </strong>instead of <strong>inheritance</strong>. Doing this allows the encapsulation of methods from your base implementation and can avoid developers to make calls of unwanted base operations like removing objects which should not allow deletion.</p><p>The example following can illustrate this pattern in .Net Core:</p><pre>namespace Domain.Repositories<br>{<br>  public interface IInvestorRepository<br>  {<br>    Investor GetWithKeys(long id);<br>    IEnumerable&lt;Investor&gt; GetAll(bool readOnly = false);<br>    IEnumerable&lt;Investor&gt; Query(Expression&lt;Func&lt;Investor, bool&gt;&gt; predicate = null, bool readOnly = false);<br>    Investor Insert(Investor entity);<br>    IEnumerable&lt;Investor&gt; InsertMany(IEnumerable&lt;Investor&gt; entities);<br>  }<br>}<br><br>namespace Data.Repositories<br>{<br>  public interface IRepository&lt;T&gt; where T : BaseEntity<br>  {<br>    T GetWithKeys(params object[] keys);<br>    IQueryable&lt;T&gt; GetAll(bool readOnly = false);<br>    IQueryable&lt;T&gt; Query(Expression&lt;Func&lt;T, bool&gt;&gt; predicate = null, bool readOnly = false);<br>    IQueryable&lt;S&gt; Query&lt;S&gt;(Expression&lt;Func&lt;S, bool&gt;&gt; predicate = null, bool readOnly = false) where S : T;<br>    T Insert(T entity);<br>    IEnumerable&lt;T&gt; InsertMany(IEnumerable&lt;T&gt; entities);<br>    T Remove(T entity);<br>    T Remove(params object[] keys);<br>    IEnumerable&lt;T&gt; RemoveMany(IEnumerable&lt;T&gt; entities);<br>    IEnumerable&lt;T&gt; RemoveMany(IEnumerable&lt;object[]&gt; keys);<br>  }<br><br>  public class InvestorRepository : IInvestorRepository<br>  {<br>    private readonly IRepository&lt;Investor&gt; _baseRepository;<br><br>    public InvestorRepository(IRepository&lt;Investor&gt; baseRepo)<br>    {<br>        _baseRepository = baseRepo;<br>    }<br>    <br>    public Investor GetWithKeys(long id) =&gt; _baseRepository.GetWithKeys(id);<br><br>    public IEnumerable&lt;Investor&gt; GetAll(bool readOnly = false) =&gt; _baseRepository.GetAll(readOnly).ToList();<br>             <br>    public IEnumerable&lt;Investor&gt; Query(Expression&lt;Func&lt;Investor, bool&gt;&gt; predicate = null, bool readOnly = false)<br>    {<br>        return _baseRepository.Query(predicate, readOnly, included).ToList();<br>    }<br>    <br>    public Investor Insert(Investor enterprise) =&gt; _baseRepository.Insert(enterprise);<br>    <br>    public IEnumerable&lt;Investor&gt; InsertMany(IEnumerable&lt;Investor&gt; enterprises) =&gt; _baseRepository.InsertMany(enterprises);<br>  }<br></pre><p><em>A Base Repository interface, a specific repository interface encapsulating exclusion methods from base interface, and a concrete repository made by composition instead of inheritance.</em></p><h4>What should a Repository Pattern Implementation never do?</h4><p>Knowing the pattern’s unique and straightforward responsibility of abstracting real data sources (example: databases) into collections of in-memory data, and keeping It doing only and exactly this, there are things to avoid entirely on the implementation to prevent an unmaintainable code, as listed below:</p><ul><li>Messing with data from outside of Its intended source table and relationship — as a violation of the <strong>Single Responsibility Principle</strong>, generating side-effects;</li><li>Usage of <strong>other repositories</strong> within the implementation — coupling treatment of unrelated tables, misplacing program logic and also violating the <strong>Open-closed and Single Responsibility Principle</strong>;</li><li>Exposing the real source of data (example: <strong>DbContexts </strong>in <strong>Entity Framework</strong> and <strong>Sessions </strong>in <strong>NHibernate</strong>) to access from out of Its inheritance, which sooner or later would result in poorly made code <strong>violating </strong>this very <strong>pattern</strong>;</li><li><strong>Commit </strong>and <strong>Rollback </strong>methods — as a common <strong>mistake </strong>while applying this pattern, forgetting to <strong>keep this </strong>for example to <strong>Unit of Work</strong> implementations, to avoid unclear code and too <strong>many database round-trips</strong> as long as repositories are not supposed to <strong>handle transactions</strong> and <strong>finish </strong>them.</li></ul><p>Also, there are other lesser evils to avoid too, but for now, let’s take only the above list before showing the real threat which motivates this article.</p><h3>Unit of Work</h3><p>Another Enterprise Pattern widely used together with the foretold one intended to manage transactions and control the submission of commands to real databases. If made wrong, It can quickly become a piece of disaster together with repositories and be kindly called <em>Unit of Rework </em>due to massive violation of other principles like DRY.</p><p>Again, this pattern has one job and is all about handle database connections to manage transactions running, so any other responsibility put inhere needlessly misplaced is also violations of software principles.</p><p>A base interface of <em>Unit Of Work</em> is short, and the concrete logic depends on your infrastructure set of technologies and packages, often having a signature with methods to do the following:</p><ul><li><strong>Begin </strong>a transaction;</li><li><strong>Save a state</strong> within a transaction;</li><li><strong>Rollback a state</strong> within a transaction;</li><li><strong>Commit </strong>and End a transaction;</li><li><strong>Rollback </strong>the transaction.</li></ul><p>We can sometimes see this pattern implementations inheriting from a base one and holding references to <em>repositories</em>, to gather the whole group of sources used in processes of that unit as a single dependency to pass on services resolving It’s logic.</p><p>The gist below represents an example of these structures:</p><pre>namespace Domain.Unities<br>{<br>  public interface IUnitOfWork : IDisposable<br>  {<br>    /// &lt;summary&gt;<br>    /// start a transaction with the context<br>    /// &lt;/summary&gt;<br>    IUnitOfWork Begin();<br><br>    /// &lt;summary&gt;<br>    /// Save state of changes in the context.<br>    /// &lt;/summary&gt;<br>    void Save();<br>    <br>    /// &lt;summary&gt;<br>    ///  Rollback all states saved under the transaction.<br>    /// &lt;/summary&gt;<br>    void RollbackStates();<br><br>    /// &lt;summary&gt;<br>    /// Confirm all changes under transaction.<br>    /// &lt;/summary&gt;<br>    void Commit();<br><br>    /// &lt;summary&gt;<br>    ///  Rollback all changes under the transaction.<br>    /// &lt;/summary&gt;<br>    void RollbackTransaction();<br>  }<br><br>  public interface IUnitOfEnterprises : IUnitOfWork<br>  {<br>    public IEnterpriseRepository Enterprises { get; }<br>    public IInvestorRepository Investors { get; }<br>    public IEnterpriseTypeRepository Types { get; }<br>  }<br>}</pre><p><em>Example of a Unit of Work base Interface Signature and a derived Unit holding repositories</em></p><p>Under this pattern, let’s list a bit of thing to be aware:</p><ul><li>Do not <strong>confuse UnitOfWork</strong> as a <strong>repository factory</strong>;</li><li>In <em>Microsoft.Net</em> platforms, do not <strong>forget to implement IDisposable </strong>interface to let the <strong>garbage collector </strong>get rid of It after Its lifetime (a request scope for example) and <strong>free tons of memory</strong> of your servers;</li><li>If holding references to <em>repositories</em>, <strong>return interfaces</strong> and <strong>do not create concrete instances manually</strong> to allow developers to <strong>mock dependencies</strong> and <strong>repositories </strong>returned;</li><li>Do not <strong>make queries</strong> or <strong>call methods from repositories</strong> to return <strong>data from your units of work </strong>code;</li><li>Derive from a <strong>Base Unit of Work interface</strong> if you want to represent a specific group of processes as a different Unit of Work.</li><li>Do not expose the real source of data (example: <strong>DbContexts </strong>in <strong>Entity Framework</strong> and <strong>Sessions </strong>in <strong>NHibernate</strong>) to access from out of Its inheritance, which leads to disaster letting developers control transactions outside your units manually<strong>.</strong></li></ul><p>On <em>Microsoft.Net</em> platforms is also possible to efficiently use <em>Unit Of Work </em>inside <em>Decorator Attributes</em> over <em>Controller Actions</em> of <em>APIs </em>or <em>MVCs </em>projects allowing developers to do more straightforward logic and less code.</p><p>To do so, inside your <em>Decorator Attribute</em>, you can get the <em>Unit Of Work</em> instance as a service within the scope created in the request, through <em>HttpContext </em>like the demonstrated following:</p><pre>namespace API.FilterAttributes<br>{<br>  public class UnitOfWorkAttribute : Attribute, IActionFilter<br>  {<br>    public IUnitOfEnterprises UnitOfWork { get; private set; }<br><br>    public void OnActionExecuting(ActionExecutingContext context)<br>    {<br>      UnitOfWork = context.HttpContext.RequestServices.GetService&lt;IUnitOfEnterprises&gt;();<br><br>      UnitOfWork.Begin();<br>    }<br><br>    public void OnActionExecuted(ActionExecutedContext context)<br>    {<br>      UnitOfWork ??= context.HttpContext.RequestServices.GetService&lt;IUnitOfEnterprises&gt;();<br><br>      if (context.Exception == null)<br>      {<br>        UnitOfWork.Commit();<br>      }<br>      else<br>      {<br>        UnitOfWork.RollbackTransaction();<br>      }<br>    }<br>  }<br>}<br><br>namespace API.Controllers<br>{<br>  [ApiController, Route(&quot;api/v1/[controller]&quot;), Produces(&quot;application/json&quot;)]<br>  [ValidateModelState]<br>  public class EnterprisesController : ControllerBase<br>  {<br>    private readonly IEnterpriseFacade _service;<br><br>    public EnterprisesController(IEnterpriseFacade service) =&gt; _service = service;<br><br>    [HttpGet]<br>    public IActionResult Get([FromQuery]EnterpriseIndexFilterInput input) =&gt; Ok(_service.ListEnterprises(input));<br><br>    [HttpGet(&quot;{id}&quot;)]<br>    public IActionResult Get(long id) =&gt; Ok(_service.GetEnterprise(id));<br><br>    [HttpPost, UnitOfWork]<br>    public IActionResult Post([FromBody] CreateEnterpriseInput input)<br>    {<br>      var enterprise = _service.CreateEnterprise(input);<br><br>      return CreatedAtAction($&quot;{nameof(Get)}&quot;, new { id = enterprise.Enterprise.Id }, enterprise);<br>    }<br><br>    [HttpPut(&quot;{id}&quot;), UnitOfWork]<br>    public IActionResult Put(long id, [FromBody] UpdateEnterpriseInput input) =&gt; Ok(_service.UpdateEnterprise(id, input));<br><br>    [HttpDelete(&quot;{id}&quot;), UnitOfWork]<br>    public IActionResult Delete(long id)<br>    {<br>      _service.DeleteEnterprise(id);<br><br>      return NoContent();<br>    }<br>  }<br>}</pre><p><em>Unit of Work usage within a decorator Action Filter Attribute in .Net Core API Controller</em></p><h3>Conclusion</h3><p>This post represents my experience seeing these concepts misunderstood out there, what I’ve learned facing these problems and also my contribution as a way to help those who still face situations working with implementations as fore described.</p><p>Hope to help you and your co-workers in this journey, and save you time maintaining messy code often present in legacy projects.</p><p>Feel free to comment, disagree, contribute and help in the discussion, always in a friendly way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52fbe05bf9a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodemonks/cautions-applying-repository-and-unit-of-work-patterns-with-dependency-injection-in-domain-driven-52fbe05bf9a5">Cautions applying Repository and Unit of Work Patterns with Dependency Injection in Domain-Driven…</a> was originally published in <a href="https://medium.com/thecodemonks">thecodemonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filling inbox with annoying tests when developing email-related features? No more!]]></title>
            <link>https://medium.com/thecodemonks/filling-inbox-with-annoying-tests-when-developing-email-related-features-no-more-d3e354f54b4c?source=rss----aebce2317dbf---4</link>
            <guid isPermaLink="false">https://medium.com/p/d3e354f54b4c</guid>
            <category><![CDATA[fake-smtp]]></category>
            <category><![CDATA[aspnet-development]]></category>
            <category><![CDATA[e-mail-testing]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Icaro Torres]]></dc:creator>
            <pubDate>Thu, 12 Sep 2019 13:18:25 GMT</pubDate>
            <atom:updated>2020-04-11T17:37:53.620Z</atom:updated>
            <content:encoded><![CDATA[<h4>Testing e-mail content in .NET without sending via SMTP. A FakeSMTP approach, thanks to Dependency injection.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHM4pc-MI3SZZXoG" /><figcaption>Photo by <a href="https://unsplash.com/@krstoj?utm_source=medium&amp;utm_medium=referral">Krsto Jevtic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When developing an application, we might face plenty of scenarios where dispatching an e-mail is required, maybe to <strong>warn a customer</strong> that something happened, alert some <strong>critical feature failure</strong>, send messages with <strong>attached files</strong>, several reasons indeed.</p><p>But while developing <strong>correlated e-mail features</strong>, It’s not a good idea to use a real SMTP client <strong>dispatching annoying test e-mails</strong> to somebody’s inbox, not even your’s.</p><p>This article will describe a <strong>Fake SMTP</strong> approach using the <strong>Dependency Injection</strong> pattern and <strong>Unit Test </strong>to help you test your e-mail contents.</p><h4>Dependency Injection</h4><p>To fully understand what is presented here, we expected you to be familiar with the mentioned pattern, but in case you don’t:</p><blockquote>“In software engineering, <strong>dependency injection</strong> is a technique whereby one object supplies the <strong>dependencies</strong> of another object. A <strong>dependency</strong> is an object that can be used, for example, as a service. The <strong>injection</strong> refers to the passing of <strong>dependency</strong> (a service) into the object (a client) that would use it.”</blockquote><p>(Wikipedia, <a href="https://en.wiki.org/wiki/Dependency_injection">https://en.wikipedia.org/wiki/Dependency_injection</a>)</p><h4>ISmtp interface</h4><p>The core of this article is the definition and usage of the simple <strong>ISmtp </strong>interface as the contract to represent our two concrete classes, <strong>Smtp</strong> and <strong>FakeStmp</strong>. In this example, the interface has one exposed method <strong>Send</strong> with logic performed by classes implementing It, and a property <strong>Sender</strong> to present the host e-mail sender.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8ec31c6d622cf18989bc323c1b8d34e/href">https://medium.com/media/a8ec31c6d622cf18989bc323c1b8d34e/href</a></iframe><h4>Smtp and FakeStmp, the concrete implementations</h4><p>Now we have a <strong>contract to fulfil</strong> with <strong>ISmtp </strong>interface. To do so, create two classes implementing <strong>ISmtp</strong>, one to perform e-mail sending behaviour expressed by <strong>Smtp</strong>, and another to <strong>test during development</strong>.</p><p>Create <strong>Smtp</strong> class encapsulating the <strong>System.Net.SmtpClient</strong> inside It and define a method <strong>Send</strong> to call the <strong>SmtpClient.Send</strong> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3df79c5da08eaeb409eb28b7d6d0614/href">https://medium.com/media/f3df79c5da08eaeb409eb28b7d6d0614/href</a></iframe><p>Notice here that the <strong>Smtp</strong> constructor receives four arguments also injected, but you can decide to get them right from <strong>Web.config </strong>or<strong> App.config</strong> files, hardcode them (extremely not recommended) or any other way you choose to pick up.</p><p>And the <strong>FakeSmtp </strong>class, instead of dispatching an e-mail to somebody’s inbox, will create an HTML file to be opened and present the message content in any web browser. Now test if the <strong>htmlString</strong> passed to “Send” is the same read from the filesystem. The implementation goes like follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb5f9b6c23668f757135d27cfbde311e/href">https://medium.com/media/eb5f9b6c23668f757135d27cfbde311e/href</a></iframe><p>As in the <strong>Smtp,</strong> the <strong>FakeSmtp </strong>constructor also has injected parameters which you can perform the same way you did on the previous class. The parameters here are used to expose the <strong>Sender </strong>and define the generated file destination on the filesystem to help differ files from each test.</p><h4>EmailWorker</h4><p>We define <em>a class </em><strong>EmailWorker</strong> with the implementation to “send” our e-mails with two parameters, as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6f569de753c0eda967c526d575c95cf/href">https://medium.com/media/c6f569de753c0eda967c526d575c95cf/href</a></iframe><p>The Send method receives two arguments:</p><ul><li>htmlString — String with the e-mail body content;</li><li>model — An instance of EmailModel containing useful data to fulfil and send the e-mail.</li></ul><p>The <strong>EmailModel </strong>defined as bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c20271ef2cf488a89ee5b0539679bdb/href">https://medium.com/media/4c20271ef2cf488a89ee5b0539679bdb/href</a></iframe><h4>The test</h4><p>Here comes the <strong>Unit Test</strong> over the <strong>FakeStmp </strong>approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0593bf2e7b2409459a17d8390a0249ca/href">https://medium.com/media/0593bf2e7b2409459a17d8390a0249ca/href</a></iframe><h4>Conclusion</h4><p>What is presented in this post is a simple approach that can become easily extendable in real-world applications. Ninject was used as a Dependency Injection Container but is totally up to you which one you’ll pick to attend this pattern.</p><p>Hope to help you get rid of filling inboxes with messages coming from e-mail related features under development, and save you from sending unwanted push notifications to your co-workers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3e354f54b4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thecodemonks/filling-inbox-with-annoying-tests-when-developing-email-related-features-no-more-d3e354f54b4c">Filling inbox with annoying tests when developing email-related features? No more!</a> was originally published in <a href="https://medium.com/thecodemonks">thecodemonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>