<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Emanuel Gustafzon</title>
    <description>The latest articles on DEV Community by Emanuel Gustafzon (@emanuelgustafzon).</description>
    <link>https://dev.to/emanuelgustafzon</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1105940%2Fa04b2a84-5b3e-421d-8f88-f979c262ce0d.gif</url>
      <title>DEV Community: Emanuel Gustafzon</title>
      <link>https://dev.to/emanuelgustafzon</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/emanuelgustafzon"/>
    <language>en</language>
    <item>
      <title>Dependency Injection Dotnet</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Tue, 31 Dec 2024 17:36:28 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/dependency-injection-dotnet-51cf</link>
      <guid>https://dev.to/emanuelgustafzon/dependency-injection-dotnet-51cf</guid>
      <description>&lt;p&gt;Welcome to the last post of this series and congrats for getting this far. You should now have a solid understanding of Dependecy Injection so let's implement it in dotnet.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lifetimes
&lt;/h2&gt;

&lt;p&gt;Dotnet support different lifetimes, Transient, Scoped and Singleton.&lt;/p&gt;

&lt;p&gt;You would tipically use Scoped in WebApps and Apis where the scoped lifetime is the lifetime of a HTTP Context. If you work in Maui or WPF etc you need to explicity create the scope and that adds extra complexity so normally you would use Transient or Singleton in those types of applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  SetUp
&lt;/h2&gt;

&lt;p&gt;You do the setup and configuration in Program.cs.&lt;/p&gt;

&lt;p&gt;If you work in Maui or ASP.NET Core, you will see that Dependecy injection is already setup but in this example we use a Console App so we need to set it up ourselves.&lt;/p&gt;

&lt;p&gt;Start off by downloading the following packages.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Microsoft.Extensions.Hosting
Microsoft.Extensions.DependencyInjection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create the default builder and configure your services&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =&amp;gt;
    {
        // Add Your Services here
    }).Build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Add collection of services
&lt;/h2&gt;

&lt;p&gt;So as you can see below you can add a collection of services with a defined lifetime.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =&amp;gt;
    {
        services.AddSingleton&amp;lt;MySingleTonService&amp;gt;();
        services.AddScoped&amp;lt;MyScopedService&amp;gt;();
        services.AddTransient&amp;lt;MyTransientService&amp;gt;();
    }).Build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Add interfaces
&lt;/h2&gt;

&lt;p&gt;You can also add a interface to the registered service which is also best practice.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =&amp;gt;
    {
        services.AddSingleton&amp;lt;IMyService, MyService&amp;gt;();
    }).Build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  IServiceProvider
&lt;/h2&gt;

&lt;p&gt;The collection of services we just configured implements the interface IServiceprovider.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =&amp;gt;
    {
        // My Collection of registered services
    }).Build();

IServiceProvider serviceProvider = host.Services;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Put it all together
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Create the Services and interfaces
&lt;/h3&gt;

&lt;p&gt;In this example we have a notification service that is dependent on an email service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface IEmailService
{
    public void SendEmail(string email, string message);
}

public class EmailService : IEmailService
{
    public void SendEmail(string email, string message)
    {
        Console.WriteLine($"Sending {message} to {email}");
    }
}
public interface INotificationService
{
    public void NotifyUser(User user, string message);
}

public class NotficationService : INotificationService
{
    IEmailService _emailService;

    public NotficationService(IEmailService emailService)
    {
        _emailService = emailService;
    }

    public void NotifyUser(User user, string message)
    {
        _emailService.SendEmail(user.Email, message);
    }
}
public class User
{
    public string Name { get; set; } = null!;
    public string Email { get; set; } = null!;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Register the services
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =&amp;gt;
    {
        services.AddTransient&amp;lt;IEmailService, EmailService&amp;gt;();
        services.AddTransient&amp;lt;INotificationService, NotficationService&amp;gt;();
    }).Build();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Access the Notification service
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var notify =  host.Services.GetRequiredService&amp;lt;INotificationService&amp;gt;();
User user = new User { Name = "Emanuel", Email = "Emanuel@domain.com" };
notify.NotifyUser(user, "Hello There!");

// output: Sending Hello There! to Emanuel@domain.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Use IServiceProvider to access services
&lt;/h2&gt;

&lt;p&gt;You can also access services through IServiceProvider. Let us rewrite the Notification Service.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class NotficationService : INotificationService
{
    IServiceProvider _serviceProvider;

    public NotficationService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void NotifyUser(User user, string message)
    {
        var emailService = _serviceProvider.GetRequiredService&amp;lt;IEmailService&amp;gt;();
        emailService.SendEmail(user.Email, message);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will work in the exact same way and we have more control over what services we want to access.&lt;/p&gt;

&lt;h2&gt;
  
  
  Different Lifetimes in action.
&lt;/h2&gt;

&lt;p&gt;So in a Console App we need to create the scope explicity so let's do that. &lt;/p&gt;

&lt;p&gt;For demostration purpose I will create a model that contains a unique ID and we will see how i singleton returns the same instance throughout the hole program and therefore the same ID. Scoped will return the same instance in the same scope and a transient will return a new instance everytime.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var host = Host.CreateDefaultBuilder()
    .ConfigureServices(services =&amp;gt;
    {
        services.AddScoped&amp;lt;UniqueIDSingelton&amp;gt;();
        services.AddScoped&amp;lt;UniqueIDScoped&amp;gt;();
        services.AddTransient&amp;lt;UniqueIDTransient&amp;gt;();
    }).Build();
public class UniqueIDSingelton
{
    public string ID = Guid.NewGuid().ToString();
}
public class UniqueIDScoped
{
    public string ID = Guid.NewGuid().ToString();
}
public class UniqueIDTransient
{
    public string ID = Guid.NewGuid().ToString();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create two scopes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var scope1 = host.Services.CreateScope();
var scope2 = host.Services.CreateScope();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let us see how a serviice with scoped lifetime behave.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var scope1 = host.Services.CreateScope();

var UniqueId1Scope1 = scope1.ServiceProvider.GetRequiredService&amp;lt;UniqueIDScoped&amp;gt;();
var UniqueId2Scope1 = scope1.ServiceProvider.GetRequiredService&amp;lt;UniqueIDScoped&amp;gt;();

Console.WriteLine(UniqueId1Scope1.ID == UniqueId2Scope1.ID); // true

var scope2 = host.Services.CreateScope();
var UniqueIdScope2 = scope2.ServiceProvider.GetRequiredService&amp;lt;UniqueIDScoped&amp;gt;();


Console.WriteLine(UniqueId1Scope1.ID == UniqueIdScope2.ID); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The instance will be the same in the same scope as you see.&lt;/p&gt;

&lt;p&gt;let us move over to Singelton. You will see that even though I get the service in two different scopes the instance and therfore the ID is the same.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var scope1 = host.Services.CreateScope();
var singeltonScope1 = scope1.ServiceProvider.GetRequiredService&amp;lt;UniqueIDSingelton&amp;gt;();

var scope2 = host.Services.CreateScope();
var singeltonScope2 = scope1.ServiceProvider.GetRequiredService&amp;lt;UniqueIDSingelton&amp;gt;();

Console.WriteLine(singeltonScope1.ID == singeltonScope2.ID); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Last let's see Transient in action and how it gives a new instance everytime. Below we call the service twice in the same scope but the instance and therefore the ID is different.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var scope1 = host.Services.CreateScope();
var transient1 = scope1.ServiceProvider.GetRequiredService&amp;lt;UniqueIDTransient&amp;gt;();
var transient2 = scope1.ServiceProvider.GetRequiredService&amp;lt;UniqueIDTransient&amp;gt;();

Console.WriteLine(transient1.ID == transient2.ID); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alright there you have Dependency Injection in Dotnet and as I told you in an ASP.NET Core Application you do not need to explicity create the scope because the scope is already configured to be the scope of a HTTP request and in other types of applications like Maui etc, you would rather use Transient and Singelton.&lt;/p&gt;

&lt;p&gt;Hope you found it useful and happy coding!&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>dependencyinversion</category>
    </item>
    <item>
      <title>Build your own DI Container in JavaScript.</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Sat, 06 Jul 2024 13:14:13 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/build-your-own-di-container-in-javascript-2da3</link>
      <guid>https://dev.to/emanuelgustafzon/build-your-own-di-container-in-javascript-2da3</guid>
      <description>&lt;h2&gt;
  
  
  What we will build
&lt;/h2&gt;

&lt;p&gt;In this chapter we will implement our own DI Container in JavaScript.&lt;/p&gt;

&lt;p&gt;We will create a checkout simulation and we are going to use our DI Container to handle the dependency injection. &lt;/p&gt;

&lt;h2&gt;
  
  
  The services
&lt;/h2&gt;

&lt;p&gt;Here is the service classes and the flow of our application. We have a credit card, a shipping bag and then a class that handles the transaction and one that sends the order.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Independent service
class CreditCard {
  owner;
  address;
  number;
  cvc;

  set(owner, address, number, cvc) {
    this.owner = owner;
    this.address = address;
    this.number = number;
    this.cvc = cvc;
  }
}
// Independent service
class ShoppingBag {
  items = [];
  total = 0;
  addItem(item) {
    this.items.push(item);
    this.total += item.price;
  }
}
// Dependent on credit card and shopping bag 
class Transaction {
  constructor(creditCard, shoppingBag) {
    this.creditCard = creditCard;
    this.shoppingBag = shoppingBag;
  }
  transfer() {
    console.log(`Transfering ${this.shoppingBag.total} to ${this.creditCard.owner}`);
  }
}

// dependent on credit card and shopping bag
class SendOrder {
  constructor(creditCard, shoppingBag) {
    this.creditCard = creditCard;
    this.shoppingBag = shoppingBag;
  }
  send() {
    console.log(`Sending ${this.shoppingBag.total} to ${this.creditCard.address}`);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  DI Container skeleton
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DIContainer {
  services = new Map();

  register() {}

  resolve() {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The DI container will have two methods, one to register the services and their dependencies and one to resolve the services and their dependencies. &lt;/p&gt;

&lt;p&gt;The services are to be saved in a map with key-value pairs of the name of the service and the service/instance.&lt;/p&gt;

&lt;h2&gt;
  
  
  Simple registration and resolving
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DIContainer {
  services = new Map();

  register(serviceName, serviceDefinition) {
    this.services.set(serviceName, {
      serviceDefinition
    });
  }

  resolve(serviceName) {
    const service = this.services.get(serviceName);

    if (!service) {
      throw new Error(`Service ${serviceName} not found`);
    }

    return new service.serviceDefinition();
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we simply register a service by adding a key-value pair in the map with the service name and the service definition. The service definition is the class. &lt;/p&gt;

&lt;p&gt;This is now like an instance generator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const container = new DIContainer();

container.register('creditCard', CreditCard);

const creditCard1 = container.resolve('creditCard');

const creditCard2 = container.resolve('creditCard');

creditCard1.set('John Doe', 'Street 12', '0000-0000-0000', '123');

creditCard2.set('Jane Smith', 'Street 2', '0000-0000-0000', '123');

console.log(creditCard1, creditCard2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Resolve dependencies
&lt;/h2&gt;

&lt;p&gt;An instance generator is not exciting so let’s add dependencies to the services. &lt;/p&gt;

&lt;p&gt;These are the steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add an array of all the names of the dependencies.&lt;/li&gt;
&lt;li&gt;Resolve all the dependencies by looping over the array and calling the resolve function on all the services. &lt;/li&gt;
&lt;li&gt;Add the resolved dependencies into the constructor of the service.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DIContainer {
  services = new Map();

  register(serviceName, serviceDefinition, dependencies = []) {
    this.services.set(serviceName, {
      serviceDefinition,
      dependencies
    });
  }

  resolve(serviceName) {
    const service = this.services.get(serviceName);

    if (!service) {
      throw new Error(`Service ${serviceName} not found`);
    }

    const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency));

    return new service.serviceDefinition(...resolvedDependencies);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it starts to be interesting. Go ahead and register the services with the dependencies array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const container = new DIContainer();

container.register('creditCard', CreditCard);
container.register('shoppingBag', ShoppingBag);
container.register('transaction', Transaction, ['creditCard', 'shoppingBag'])

const creditCard= container.resolve('creditCard');
const shoppingBag = container.resolve('shoppingBag');

creditCard.set('John Doe', 'Street 12', '0000-0000-0000', '123');
shoppingBag.addItem({name: 'Apple', price: 1.99});

container.resolve('transaction').transfer();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It works BUT in the console, we get &lt;code&gt;Transfering 0 to undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;That's because of &lt;code&gt;scope&lt;/code&gt;. the data from the credit card and shopping bag does not persist because our container creates a new instance every time it is called. It has a transient scope. &lt;/p&gt;

&lt;h1&gt;
  
  
  Add Scope
&lt;/h1&gt;

&lt;p&gt;Let's add scope to our container. by adding a scope parameter in the register function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  register(serviceName, serviceDefinition, scope, dependencies = []) {
    this.services.set(serviceName, {
      serviceDefinition,
      scope,
      dependencies
    });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Add Transient
&lt;/h3&gt;

&lt;p&gt;Our container already provides transient services but let's add an if statement for when it is transient and add the logic there.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  resolve(serviceName) {
    const service = this.services.get(serviceName);

    if (!service) {
      throw new Error(`Service ${serviceName} not found`);
    }
    if (service.scope === 'transient') {
      const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency));

      return new service.serviceDefinition(...resolvedDependencies);
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Add Singleton
&lt;/h3&gt;

&lt;p&gt;Let's also add support for singleton services. By doing so check if an instance already exists and if it does return the existing instance and don't create a new one.&lt;/p&gt;

&lt;p&gt;In the resister function insiste an instance key in services and set it to null.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
register(serviceName, serviceDefinition, scope, dependencies = []) {
    this.services.set(serviceName, {
      serviceDefinition,
      scope,
      dependencies,
      instance: null // add instance property to store the instance of the service
    });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the resolve method add an if statement for singleton and always return the same instance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (service.scope === 'singleton') {
        if (!service.instance) {
            const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency));
            service.instance = new service.serviceDefinition(...resolvedDependencies);
        }
        return service.instance;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s register the credit card and shopping bag as singleton and the transaction as transient.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const container = new DIContainer();

container.register('creditCard', CreditCard, 'singleton');
container.register('shoppingBag', ShoppingBag, 'singleton');
container.register('transaction', Transaction, 'transient',['creditCard', 'shoppingBag'])

const creditCard= container.resolve('creditCard');
const shoppingBag = container.resolve('shoppingBag');

creditCard.set('John Doe', 'Street 12', '0000-0000-0000', '123');
shoppingBag.addItem({name: 'Apple', price: 1.99});

container.resolve('transaction').transfer();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And we get &lt;code&gt;Transfering 1.99 to John Doe&lt;/code&gt; in the console.&lt;/p&gt;

&lt;p&gt;BUT we are not there yet because the shopping bag and credit card will always have the same instance you can set different values but the instance is the same. So new users cannot add new cards or shopping bags.&lt;/p&gt;

&lt;p&gt;watch the code below. We cannot resolve the credit card and shopping bag in different contexts. Let's add 2 cards and 2 bags and you see what I mean.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const creditCard= container.resolve('creditCard');
const shoppingBag = container.resolve('shoppingBag');

const creditCard2 = container.resolve('creditCard');
const shoppingBag2 = container.resolve('shoppingBag');

creditCard.set('John Doe', 'Street 12', '0000-0000-0000', '123');
shoppingBag.addItem({name: 'Apple', price: 1.99});

creditCard2.set('Dan Scott', 'Street 90', '1111-1111-1111', '321');
shoppingBag2.addItem({name: 'Orange', price: 2.99});

container.resolve('transaction').transfer();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Add Request/Scoped
&lt;/h3&gt;

&lt;p&gt;We need to add an HTTP context to our container. Let's add a context parameter to the resolve method and a &lt;code&gt;Map&lt;/code&gt; hashtable to save the scoped services.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DIContainer {
  services = new Map();
  scopedServices = new Map(); // save the scoped services

  register(serviceName, serviceDefinition, scope, dependencies = []) {}

  // Add context
  resolve(serviceName, context = null) {}

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Cool, add an if statement for scoped lifetimes in the resolve method.&lt;/p&gt;

&lt;p&gt;Check if there is a context otherwise throw an error. &lt;/p&gt;

&lt;p&gt;check if the current context already exists in the scopedServices Map otherwise create it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if(service.scope === 'scoped') {
        if (!context) {
                throw new Error('Scoped services requires a context.');
            }

            if (!this.scopedServices.has(context)) {
                // key value pair of context and a new map with the services
                this.scopedServices.set(context, new Map());
            }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have saved the context, let's find the saved context, add the service name and its instance, as well as the dependencies names and instances, and then resolve them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if(service.scope === 'scoped') {
        if (!context) {
                throw new Error('Scoped services requires a context.');
            }

            if (!this.scopedServices.has(context)) {
                this.scopedServices.set(context, new Map());
            }
            const contextServices = this.scopedServices.get(context);

            if (!contextServices.has(serviceName)) {
                const resolvedDependencies = service.dependencies.map(dependency=&amp;gt; this.resolve(dependency, context)); // Don't forget to include context
                const instance = new service.serviceDefinition(...resolvedDependencies);
                  contextServices.set(serviceName, instance);
            }

            return contextServices.get(serviceName);
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The structure of the scoped services looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ 
context1: {
            serviceName: instance,
            serviceName: instance
           },
context2: {
            serviceName: instance,
            serviceName: instance
           }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also need to pass the context to all dependencies being resolved. so let's do that also for transient and singleton services.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (service.scope === 'transient') {
      // pass the context into dependencies
      const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency, context)); 

      return new service.serviceDefinition(...resolvedDependencies);
    }

if (service.scope === 'singleton') {
        if (!service.instance) {
            // pass the context into dependencies
            const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency, context));
            service.instance = new service.serviceDefinition(...resolvedDependencies);
        }
        return service.instance;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Remove context
&lt;/h4&gt;

&lt;p&gt;Now let's add a function that cleans up the scoped services. &lt;/p&gt;

&lt;p&gt;We add one extra method to our DI Container called clearContext.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;clearContext(context) {
          this.scopedServices.delete(context);
          console.log("Deleted context");
      }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Let's try it out.
&lt;/h4&gt;

&lt;p&gt;We simulate a httpContext by creating an httpContextobject and sending it as an argument to the resolve function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const container = new DIContainer();

container.register('creditCard', CreditCard, 'scoped');
container.register('shoppingBag', ShoppingBag, 'scoped');
container.register('transaction', Transaction, 'transient',['creditCard', 'shoppingBag'])
container.register('sendOrder', SendOrder, 'transient',['creditCard', 'shoppingBag'])

const httpContext = {
  headers: {
    "content-type": "application/json"
  },
  body: {
    url: "https://www.myStore.com/checkout"
  }
}
const httpContext2 = {
  headers: {
    "content-type": "application/json"
  },
  body: {
    url: "https://www.myStore.com/checkout"
  }
}

const creditCard = container.resolve('creditCard', httpContext);
const shoppingBag = container.resolve('shoppingBag', httpContext);

const creditCard2 = container.resolve('creditCard', httpContext2);
const shoppingBag2 = container.resolve('shoppingBag', httpContext2);

creditCard.set('John Doe', 'Street 12', '0000-0000-0000', '123');
shoppingBag.addItem({name: 'Apple', price: 1.99});

creditCard2.set('Dan Scott', 'Street 90', '1111-1111-1111', '321');
shoppingBag2.addItem({name: 'Orange', price: 2.99});

container.resolve('transaction', httpContext).transfer();
container.resolve('transaction', httpContext2).transfer();

container.clearContext(httpContext);
container.clearContext(httpContext2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the console  you should see:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Transfering 1.99 to John Doe&lt;br&gt;
Transfering 2.99 to Dan Scott&lt;br&gt;
Deleted context&lt;br&gt;
Deleted context&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Thanks for reading and happy coding!&lt;/p&gt;

&lt;h4&gt;
  
  
  Full example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DIContainer {
  services = new Map();
  scopedServices = new Map();

  register(serviceName, serviceDefinition, scope, dependencies = []) {
    this.services.set(serviceName, {
      serviceDefinition,
      scope,
      dependencies,
      instance: null 
    });
  }
  resolve(serviceName, context = null) {
    const service = this.services.get(serviceName);

    if (!service) {
      throw new Error(`Service ${serviceName} not found`);
    }
    if (service.scope === 'transient') {
      const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency, context));

      return new service.serviceDefinition(...resolvedDependencies);
    }

    if (service.scope === 'singleton') {
        if (!service.instance) {
            const resolvedDependencies = service.dependencies.map(dependency =&amp;gt; this.resolve(dependency, context));
            service.instance = new service.serviceDefinition(...resolvedDependencies);
        }
        return service.instance;
    }
    if(service.scope === 'scoped') {
        if (!context) {
                throw new Error('Scoped services requires a context.');
            }

            if (!this.scopedServices.has(context)) {
                this.scopedServices.set(context, new Map());
            }
            const contextServices = this.scopedServices.get(context);

            if (!contextServices.has(serviceName)) {
                const resolvedDependencies = service.dependencies.map(dependency=&amp;gt; this.resolve(dependency, context)); 
                const instance = new service.serviceDefinition(...resolvedDependencies);
                  contextServices.set(serviceName, instance);
            }

            return contextServices.get(serviceName);
    }
  }
  clearContext(context) {
        this.scopedServices.delete(context);
        console.log('Deleted context');
    }
}

// Independent service
class CreditCard {
  owner;
  address;
  number;
  cvc;

  set(owner, address, number, cvc) {
    this.owner = owner;
    this.address = address;
    this.number = number;
    this.cvc = cvc;
  }
}
// Independent service
class ShoppingBag {
  items = [];
  total = 0;
  addItem(item) {
    this.items.push(item);
    this.total += item.price;
  }
}
// Dependent on credit card and shopping bag 
class Transaction {
  constructor(creditCard, shoppingBag) {
    this.creditCard = creditCard;
    this.shoppingBag = shoppingBag;
  }
  transfer() {
    console.log(`Transfering ${this.shoppingBag.total} to ${this.creditCard.owner}`);
  }
}

// dependent on credit card and shopping bag
class SendOrder {
  constructor(creditCard, shoppingBag) {
    this.creditCard = creditCard;
    this.shoppingBag = shoppingBag;
  }
  send() {
    console.log(`Sending ${this.shoppingBag.total} to ${this.creditCard.address}`);
  }
}

const container = new DIContainer();

container.register('creditCard', CreditCard, 'scoped');
container.register('shoppingBag', ShoppingBag, 'scoped');
container.register('transaction', Transaction, 'transient',['creditCard', 'shoppingBag'])
container.register('sendOrder', SendOrder, 'transient',['creditCard', 'shoppingBag'])

const httpContext = {
  headers: {
    "content-type": "application/json"
  },
  body: {
    url: "https://www.myStore.com/checkout"
  }
}
const httpContext2 = {
  headers: {
    "content-type": "application/json"
  },
  body: {
    url: "https://www.myStore.com/checkout"
  }
}

const creditCard = container.resolve('creditCard', httpContext);
const shoppingBag = container.resolve('shoppingBag', httpContext);

const creditCard2 = container.resolve('creditCard', httpContext2);
const shoppingBag2 = container.resolve('shoppingBag', httpContext2);

creditCard.set('John Doe', 'Street 12', '0000-0000-0000', '123');
shoppingBag.addItem({name: 'Apple', price: 1.99});

creditCard2.set('Dan Scott', 'Street 90', '1111-1111-1111', '321');
shoppingBag2.addItem({name: 'Orange', price: 2.99});

container.resolve('transaction', httpContext).transfer();
container.resolve('transaction', httpContext2).transfer();

container.clearContext(httpContext);
container.clearContext(httpContext2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>dependencyinversion</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>What is a DI Container?</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Fri, 05 Jul 2024 14:54:14 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/what-is-a-di-container-468h</link>
      <guid>https://dev.to/emanuelgustafzon/what-is-a-di-container-468h</guid>
      <description>&lt;p&gt;In the last post in this series we learned about dependency injection. &lt;/p&gt;

&lt;p&gt;We saw that we needed to manually create an instance of the database connection class before creating an instance of the post routes class. Then, we passed the connection instance into the constructor of the posts object.&lt;/p&gt;

&lt;p&gt;Imagine, though, if we could just create an instance of the post routes class, and the system itself would automatically know that the posts class depends on a database connection and create that instance for us 💡.&lt;/p&gt;

&lt;p&gt;There you have it! A Dependency Injection Container is doing just that. &lt;/p&gt;

&lt;p&gt;A DI Container is responsible for creating instances of classes and managing their dependencies. Here’s a more detailed breakdown:&lt;/p&gt;

&lt;h2&gt;
  
  
  Registering Services
&lt;/h2&gt;

&lt;p&gt;First, you register your classes with the container and specify their dependencies. For example, you tell the container that PostRoutes depends on a DatabaseConnection.&lt;/p&gt;

&lt;h2&gt;
  
  
  Resolving Services
&lt;/h2&gt;

&lt;p&gt;When you ask the container to resolve a service (i.e., create an instance of a class), the container:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Creates an instance of the class.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Resolves all the dependencies that the class needs by creating instances of those dependencies as well.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This means that the container automatically creates and injects instances of all the required dependencies, simplifying the process of creating complex objects with multiple dependencies.&lt;/p&gt;

&lt;h1&gt;
  
  
  The lifetime of instances.
&lt;/h1&gt;

&lt;p&gt;You need to keep in mind how long an instance live before it gets renewed. We call this scope. &lt;/p&gt;

&lt;p&gt;The 3 most common scopes are &lt;code&gt;transient&lt;/code&gt;, &lt;code&gt;singleton&lt;/code&gt; and &lt;code&gt;request&lt;/code&gt; or even called &lt;code&gt;scoped&lt;/code&gt; in .NET. &lt;/p&gt;

&lt;h2&gt;
  
  
  Singleton
&lt;/h2&gt;

&lt;p&gt;The singleton scope means that the DI Container creates one instance of the service and keeps that same instance throughout the program’s lifetime. Every time you resolve the service, you get the same instance. This is useful for services that maintain state or are expensive to create and should be shared across the entire application.&lt;/p&gt;

&lt;h5&gt;
  
  
  Example: Logging Service
&lt;/h5&gt;

&lt;p&gt;A logging service that logs messages to the console can be a good use case for a singleton service. A logging service keeps the same state and stay consistent throughout the program.&lt;/p&gt;

&lt;h2&gt;
  
  
  Transient
&lt;/h2&gt;

&lt;p&gt;Transient scope means that the DI Container creates a new instance of the service each time it is resolved. This is useful for lightweight, stateless services where each operation should be independent of others.&lt;/p&gt;

&lt;h5&gt;
  
  
  Example: Unique ID Generation Service
&lt;/h5&gt;

&lt;p&gt;A service that generates unique IDs might be a good use case for a transient service. Each request to this service should produce a new, unique value without retaining any state from previous requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Scoped or Request
&lt;/h2&gt;

&lt;p&gt;Scoped services last as long as the HttpContext lasts. This scope is particularly useful in web applications.&lt;/p&gt;

&lt;p&gt;When working in the backend, you receive HTTP requests from clients. Each request has a context, known as the HttpContext, which lasts from when the client sends the request to the backend until the backend sends a response back to the client. During this period, multiple operations might occur, such as connecting to a database, fetching data to authorize the user, retrieving various resources, etc.&lt;/p&gt;

&lt;h5&gt;
  
  
  Example: Database Connection Service
&lt;/h5&gt;

&lt;p&gt;For a database connection service, you want the same instance to be used throughout the entire HttpContext to avoid losing the connection during the request processing. This ensures that the database connection remains consistent and efficient throughout the lifecycle of the request.&lt;/p&gt;

&lt;h5&gt;
  
  
  Stay tuned because in the next chapter we will start building our own DI container in JavaScript.
&lt;/h5&gt;

</description>
      <category>programming</category>
      <category>dependencyinversion</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>Dependency Injection made simple.</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Fri, 05 Jul 2024 11:17:54 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/dependency-injection-made-simple-3d4c</link>
      <guid>https://dev.to/emanuelgustafzon/dependency-injection-made-simple-3d4c</guid>
      <description>&lt;p&gt;Dependency Injection is an intimitating word. But actually the concept is quite simple.&lt;/p&gt;

&lt;p&gt;Dependency Injection is a way of handling &lt;code&gt;objects&lt;/code&gt; that are &lt;code&gt;dependent&lt;/code&gt; on &lt;code&gt;other objects&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;We will make an implementation in &lt;code&gt;JavaScript&lt;/code&gt; and then in &lt;code&gt;C# with interfaces.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let’s start with a simple example of an object being dependent of another object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DatabaseConnection {
  connect() {
    console.log("Connected to database");
  }
}

class PostsRouter {
  get() {
    const db = new DatabaseConnection();
    db.connect();
    console.log("Posts retrieved");
  }
}
const posts = new PostsRouter;
posts.get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above the posts router is dependent on the database connection. &lt;/p&gt;

&lt;p&gt;BUT there is a problem here. Even though this solution works, it’s not flexible. The code is, as we say tightly coupled.&lt;/p&gt;

&lt;p&gt;What if you have two different database connections? One for SQLite and one for MySQL? To change the connection object you need to change the code in the posts route. &lt;/p&gt;

&lt;p&gt;That’s when dependency injection comes in. &lt;/p&gt;

&lt;p&gt;Dependency injection is basically nothing more than &lt;code&gt;passing an object&lt;/code&gt; into the &lt;code&gt;constructor&lt;/code&gt; or &lt;code&gt;setter&lt;/code&gt; of a &lt;code&gt;class&lt;/code&gt; that depends on that object.&lt;/p&gt;

&lt;p&gt;Let’s try that!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class SQLiteConnection {
  connect() {
    console.log("Connected to SQlite");
  }
}

class MySqlConnection {
  connect() {
    console.log("Connected to MySQL");
  }
}

class PostsRouter {
  constructor(connection) {
    this.connection = connection;
  }
  get() {
    this.connection.connect();
    console.log("Posts retrieved");
  }
}

const mySql = new MySqlConnection;
const sqlite = new SQLiteConnection;

const mysqlPosts = new PostsRouter(mySql);

const sqlitePosts = new PostsRouter(sqlite);

mysqlPosts.get();
sqlitePosts.get();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You see! This makes the code more flexible. The connection object is decoupled from the posts object. You can pass any object to the constructor. &lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The code is decoupled and easier to manage. &lt;/li&gt;
&lt;li&gt;The code is easier to test. You can create a mock object and pass it to the post router.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Interfaces
&lt;/h2&gt;

&lt;p&gt;You might have noticed that our implementation worked fine in JavaScript because we don’t need to think about types. &lt;/p&gt;

&lt;p&gt;But many times we work with strongly typed languages like TypeScript, C# and Java. &lt;/p&gt;

&lt;p&gt;So the issue is when we send the connection object into the posts object we need to define a type. &lt;/p&gt;

&lt;p&gt;That’s why we need interfaces. Interfaces is like classes but there is no implementation of methods or properties it’s just the types. &lt;/p&gt;

&lt;p&gt;Let’s implement an interface for the connection objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface IDb {
  public void connect();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the structure of the connection object. It has a public method called connect and it returns void and has no parameters. &lt;/p&gt;

&lt;p&gt;Now the connection classes can inherit from IDb to enforce the same structure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class SQLiteConnection : IDb {
  public void connect() {
    Console.WriteLine("Connected to SQlite");
  }
}

class MySqlConnection : IDb {
  public void connect() {
    Console.WriteLine("Connected to MySQL");
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s worth noticing, that a class can inherit multiple interfaces in most languages. &lt;/p&gt;

&lt;p&gt;Now we can pass the connection objects in the constructor of the posts route object using IDb as the type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
class PostsRouter {
  IDb _connection;

  public PostsRouter(IDb connection) {
    this._connection = connection;
  }
  public void get() {
    this._connection.connect();
    Console.WriteLine("Posts retrieved");
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this explanation made sense to you! &lt;/p&gt;

&lt;p&gt;Here is the full example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
using System;

interface IDb {
  public void connect();
}

class SQLiteConnection : IDb {
  public void connect() {
    Console.WriteLine("Connected to SQlite");
  }
}

class MySqlConnection : IDb {
  public void connect() {
    Console.WriteLine("Connected to MySQL");
  }
}

class PostsRouter {
  IDb _connection;

  public PostsRouter(IDb connection) {
    this._connection = connection;
  }
  public void get() {
    this._connection.connect();
    Console.WriteLine("Posts retrieved");
  }
}

class Program {
  public static void Main (string[] args) {
    IDb sqlConnection = new SQLiteConnection();
    IDb mySqlConnection = new MySqlConnection();

    PostsRouter posts = new PostsRouter(sqlConnection);
    PostsRouter posts2 = new PostsRouter(mySqlConnection);
    posts.get();
    posts2.get();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>csharp</category>
      <category>interfaces</category>
      <category>dependencyinjection</category>
    </item>
    <item>
      <title>Understand DI Containers: Intro</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Fri, 05 Jul 2024 09:59:37 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/understand-di-containers-intro-353a</link>
      <guid>https://dev.to/emanuelgustafzon/understand-di-containers-intro-353a</guid>
      <description>&lt;p&gt;I’m excited to start this new series and dig deeper into dependency injection!! &lt;/p&gt;

&lt;p&gt;We are going to use JavaScript and C# in this series.&lt;/p&gt;

&lt;p&gt;After this tutorial we will have a solid understanding of DI Containers and be able to adopt our knowledge when we work with frameworks like &lt;code&gt;.Net&lt;/code&gt;, &lt;code&gt;Spring Boot&lt;/code&gt; and &lt;code&gt;Nest.JS&lt;/code&gt; etc 😎. &lt;/p&gt;

&lt;h2&gt;
  
  
  What we will learn.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;What is Dependency Injection.&lt;/li&gt;
&lt;li&gt;What are interfaces.&lt;/li&gt;
&lt;li&gt;Create a &lt;code&gt;DI Container from scratch&lt;/code&gt; with different life cycles using JavaScript. &lt;/li&gt;
&lt;li&gt;Use the DI Container in .NET. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We are going to take it one step at the time, stay tuned! &lt;/p&gt;

</description>
      <category>ioc</category>
      <category>depenedencyinjection</category>
      <category>javascript</category>
      <category>csharp</category>
    </item>
    <item>
      <title>SQL Course: Challanges</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Tue, 02 Jul 2024 10:25:44 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/sql-course-challanges-3fa7</link>
      <guid>https://dev.to/emanuelgustafzon/sql-course-challanges-3fa7</guid>
      <description>&lt;p&gt;Alright, great job for coming this far. It’s time for some challenges to finalize our social media database. &lt;/p&gt;

&lt;h2&gt;
  
  
  Challenges overview
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Query all posts and order them based on number of likes.&lt;/li&gt;
&lt;li&gt;Query a users followers profiles and the posts they have liked.&lt;/li&gt;
&lt;li&gt;Add comments to the posts. &lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Here is the tables we have created so far and the inserted data.
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Users 
(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  Username VARCHAR(255) UNIQUE NOT NULL,
  Password VARCHAR(255) NOT NULL,
  CHECK (LENGTH(Password) &amp;gt; 5)
);
-- one to one field user and profile
CREATE TABLE Profiles
(
  UserID INTEGER NOT NULL PRIMARY KEY,
  Img VARCHAR(1),
  Bio TEXT,
  FOREIGN KEY (UserID) REFERENCES Users(ID)
);
-- one to many field user and post
CREATE TABLE Posts
(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  UserID INTEGER NOT NULL,
  Title VARCHAR(255) NOT NULL,
  Content TEXT NOT NULL,
  FOREIGN KEY (UserID) REFERENCES Users(ID)
);
-- many to many field user likes posts
CREATE TABLE Likes
(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  PostID INTEGER,
  UserID INTEGER, 
  FOREIGN KEY (PostID) REFERENCES Posts(ID),
  FOREIGN KEY (UserID) REFERENCES Users(ID)
);
-- many to many field user follows users
CREATE TABLE Follows
  (
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  OwnerID INTEGER,
  FollowingID INTEGER,
  FOREIGN KEY (OwnerID) REFERENCES Users(ID),
  FOREIGN KEY (FollowingID) REFERENCES Users(ID)
  );

INSERT INTO Users (Username, Password) VALUES 
  ('Ben', 'secret'),
  ('Jim', 'secret'),
  ('Luk', 'secret');

INSERT INTO Profiles (UserID, Img, BIO) VALUES
  (1, '😎', 'I am a cool guy'), --Ben
  (2, '🥳', 'I love party'), --Jim
  (3, '🤠', 'I am a cowboy'); --Luk

INSERT INTO Posts (UserID, Title, Content) VALUES 
   (1, 'sql', 'sql content'),
   (1, 'java', 'java content'),
   (2, 'NLP', 'NLP Content'),
   (2, 'rust', 'rust content');

INSERT INTO Likes (UserID, PostID) VALUES
  (1, 1), -- Ben likes sql
  (2, 1), -- Jim likes sql
  (3, 1), -- Luk likes sql
  (1, 2), -- Ben likes Java
  (3, 3); -- Luk likes NLP

INSERT INTO Follows (OwnerID, FollowingID) VALUES
  (1, 2), -- ben follow jim
  (2, 1), -- jim folliw ben
  (2, 3), -- jim follow luk
  (3, 1), -- luk follow ben
  (1, 3); -- ben follow luk

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Challenge 1
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Query all posts and order them after number of likes. &lt;/li&gt;
&lt;li&gt;The posts with the most likes should come first. &lt;/li&gt;
&lt;li&gt;The tricky part is to include posts that have 0 likes. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tip: Use a right join.&lt;/p&gt;

&lt;p&gt;Expected result:&lt;/p&gt;

&lt;p&gt;A table of post title, post content and number of likes. &lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 2
&lt;/h2&gt;

&lt;p&gt;In this challenge you will get some starter code. &lt;/p&gt;

&lt;p&gt;This code return all user profiles, Jim follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT 
followsUser.Username,
followsProfile.Img,
followsProfile.Bio
FROM Follows f 
JOIN Users u ON f.OwnerID = u.ID
JOIN Users followsUser ON f.FollowingID = followsUser.ID
JOIN Profiles followsProfile ON followsProfile.UserID = followsUser.ID
WHERE u.Username = 'Jim';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your challenge is to add on to this. So that it returns the profile and the posts the followed users have &lt;code&gt;liked&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Expected result: &lt;/p&gt;

&lt;p&gt;A table of, username, profile image, profile bio, the user’s post with title and content.&lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 3
&lt;/h2&gt;

&lt;p&gt;We want a feature where users can comment on posts. &lt;/p&gt;

&lt;p&gt;Each comment is associated with one post and one user. &lt;/p&gt;

&lt;p&gt;Share your solutions in comments. Thanks for reading and happy coding! &lt;/p&gt;

</description>
      <category>sql</category>
      <category>challenge</category>
    </item>
    <item>
      <title>SQL Course: Self Join</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Mon, 01 Jul 2024 21:45:41 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/sql-course-self-join-5g0g</link>
      <guid>https://dev.to/emanuelgustafzon/sql-course-self-join-5g0g</guid>
      <description>&lt;p&gt;It’s time to add followers to our database application. &lt;/p&gt;

&lt;p&gt;We will establish one more many-to-many relationship. Our join table will be the followers table. &lt;/p&gt;

&lt;p&gt;The interesting thing with this table is that is the two foreign keys are referencing the same table, the users table. Therefore we need to query the followers with a self join. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.w3schools.com/sql/sql_join_self.asp" rel="noopener noreferrer"&gt;Read more about self joins.&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Create the join table
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The OwnerID is the user who follow another user.&lt;/li&gt;
&lt;li&gt;The FollowingID is the user who is being followed.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Follows
  (
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  OwnerID INTEGER,
  FollowingID INTEGER,
  FOREIGN KEY (OwnerID) REFERENCES Users(ID),
  FOREIGN KEY (FollowingID) REFERENCES Users(ID)
  );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Insert data
&lt;/h2&gt;

&lt;p&gt;Ex user with ID 1, Ben follow user with ID 2, Jim.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO Follows (OwnerID, FollowingID) VALUES
  (1, 2),
  (2, 1),
  (2, 3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Query with self join.
&lt;/h2&gt;

&lt;p&gt;In this query we retrieve all users and the users they follow and then group by user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT 
owner.username, followsUser.Username
FROM Follows f
JOIN Users owner ON f.OwnerID = owner.ID
JOIN Users followsUser ON f.FollowingID = followsUser.ID
GROUP BY owner.username, followsUser.Username;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also get all the users a particular user is following.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT 
owner.username, followsUser.Username
FROM Follows f
JOIN Users owner ON f.OwnerID = owner.ID
JOIN Users followsUser ON f.FollowingID = followsUser.ID
WHERE owner.Username = 'Ben';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>sql</category>
    </item>
    <item>
      <title>SQL Course: Many-to-many relationship and Nested Joins.</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Mon, 01 Jul 2024 20:24:21 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/sql-course-many-to-many-relationship-and-nested-joins-4c28</link>
      <guid>https://dev.to/emanuelgustafzon/sql-course-many-to-many-relationship-and-nested-joins-4c28</guid>
      <description>&lt;p&gt;You have learned about one-to-one and one-to-many relationships and they are quite straight forward. Many-to-Many works a bit different because you need an extra table, so called join table. &lt;/p&gt;

&lt;p&gt;In this example we will let users like posts in the database. To achieve this functionality we need to create a many-to-many relationship because a user can like many posts and a post can have many likes.&lt;/p&gt;

&lt;p&gt;To establish this relationship we need a join table that holds a reference to the user who likes the post and the post that is being liked. &lt;/p&gt;

&lt;h3&gt;
  
  
  Create a likes table that function as a join table.
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Likes
(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  PostID INTEGER,
  UserID INTEGER, 
  FOREIGN KEY (PostID) REFERENCES Posts(ID),
  FOREIGN KEY (UserID) REFERENCES Users(ID)
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Insert data to the likes table.
&lt;/h2&gt;

&lt;p&gt;We add the user’s ID and the post’s ID. Ex user 1, Ben likes post 1 about sql.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO Likes (UserID, PostID) VALUES
  (1, 1),
  (2, 1),
  (3, 1), 
  (1, 2),
  (2, 2),
  (3, 3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Nested Join
&lt;/h2&gt;

&lt;p&gt;To be able to query data from a many-to-many relationship we need nested joins.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Select the fields to retrieve.&lt;/li&gt;
&lt;li&gt;Use the join table as starting point, our likes table. &lt;/li&gt;
&lt;li&gt;Join the related data, in our case the users and the posts.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT 
u.Username, p.Title, p.Content
FROM Likes l
JOIN Users u ON l.UserID = u.ID
JOIN Posts p ON l.PostID = p.ID;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To make the result more readable let’s group users and the posts they liked together.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT 
u.Username, p.Title, p.Content
FROM Likes l
JOIN Users u ON l.UserID = u.ID
JOIN Posts p ON l.PostID = p.ID
GROUP BY u.ID, p.ID;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;/p&gt;

&lt;p&gt;Ben | sql | sql content&lt;br&gt;
Ben | java | java content&lt;br&gt;
Jim | sql | sql content&lt;br&gt;
Jim | java | java content&lt;br&gt;
Luk | sql | sql content&lt;br&gt;
Luk | NLP | NLP content&lt;/p&gt;

</description>
      <category>sql</category>
    </item>
    <item>
      <title>SQL Course: One-to-many Relationships and Left Joins</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Mon, 01 Jul 2024 19:05:57 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/sql-course-one-to-many-relationships-and-left-joins-pgm</link>
      <guid>https://dev.to/emanuelgustafzon/sql-course-one-to-many-relationships-and-left-joins-pgm</guid>
      <description>&lt;p&gt;In the last chapter we learned about one-to-one fields and inner joins. In this chapter we learn about one-to-many relationships and left joins. If you followed the last chapter this should be easy. &lt;/p&gt;

&lt;p&gt;We will create a &lt;code&gt;posts table&lt;/code&gt; and a &lt;code&gt;post is related to one user&lt;/code&gt; and a &lt;code&gt;user can have many posts&lt;/code&gt;. That is why it is called a one-to-many relationship.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites with links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_join_left.asp" rel="noopener noreferrer"&gt;Left Joins&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Create the posts table
&lt;/h2&gt;

&lt;p&gt;We create the post table with its own primary key and a foreign key to the user's table. &lt;/p&gt;

&lt;p&gt;By letting the posts table have an independent primary key there is no restriction of multiple posts having the same foreign key.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Posts
(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  UserID INTEGER NOT NULL,
  Title VARCHAR(255) NOT NULL,
  Content TEXT NOT NULL,
  FOREIGN KEY (UserID) REFERENCES Users(ID)
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Insert data to the posts table
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO Posts (UserID, Title, Content) VALUES 
   (1, 'sql', 'sql content'),
   (1, 'java', 'java content'),
   (2, 'NLP', 'NLP content'),
   (2, 'rust', 'rust content');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Query with a left join.
&lt;/h2&gt;

&lt;p&gt;We will make a query where we get all the users and if the user has a post we retrieve that post.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT u.Username, p.Title, p.Content
FROM Users u
LEFT JOIN Posts p ON u.ID = p.UserID;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result: &lt;br&gt;
Ben | java | java content&lt;br&gt;
Ben | sql  | sql content&lt;br&gt;
Jim | NLP  | NLP Content&lt;br&gt;
Jim | rust | rust content&lt;br&gt;
Luk |      | &lt;/p&gt;

</description>
      <category>sql</category>
    </item>
    <item>
      <title>SQL Course: One-to-one Relationships and Inner Joins.</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Mon, 01 Jul 2024 17:28:37 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/sql-course-one-to-one-relationships-and-inner-joins-4e9g</link>
      <guid>https://dev.to/emanuelgustafzon/sql-course-one-to-one-relationships-and-inner-joins-4e9g</guid>
      <description>&lt;p&gt;In this chapter, we will set up a user and a profile table and create a one-to-one relationship between them. &lt;/p&gt;

&lt;p&gt;A user can create a &lt;code&gt;user&lt;/code&gt; with a username and password and then create a &lt;code&gt;profile&lt;/code&gt; with a profile image and bio. A user can only have one profile and a profile can only be related to one user. That is why it is called a one-to-one relationship.&lt;/p&gt;

&lt;p&gt;If you use &lt;code&gt;Replit&lt;/code&gt;, create the template for &lt;code&gt;SQLite&lt;/code&gt; and you are good to go. &lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites with links
&lt;/h2&gt;

&lt;p&gt;Press the links to read more about the topic;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_create_table.asp" rel="noopener noreferrer"&gt;Create a table &lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_primarykey.asp" rel="noopener noreferrer"&gt;Primary Keys&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_foreignkey.asp" rel="noopener noreferrer"&gt;Foreign Keys&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_autoincrement.asp" rel="noopener noreferrer"&gt;Autoincrement&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_datatypes.asp" rel="noopener noreferrer"&gt;Data types&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_join_inner.asp" rel="noopener noreferrer"&gt;Inner join&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_constraints.asp" rel="noopener noreferrer"&gt;Contraints&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/sql/sql_alias.asp" rel="noopener noreferrer"&gt;Aliases&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Create the tables.
&lt;/h2&gt;

&lt;p&gt;Leave out the primary and foreign keys in the profile table for now. We use the constraint &lt;code&gt;CHECK&lt;/code&gt; to make sure the password has a length of more than 5 characters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Users 
(
  ID INTEGER PRIMARY KEY AUTOINCREMENT,
  Username VARCHAR(255) UNIQUE NOT NULL,
  Password VARCHAR(255) NOT NULL,
  CHECK (LENGTH(Password) &amp;gt; 5)
);

CREATE TABLE Profiles 
(
  Img VARCHAR(1),
  Bio TEXT
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Establish the one-to-one relationship.
&lt;/h2&gt;

&lt;p&gt;To make sure a user only can create one profile, we can use the &lt;code&gt;user’s primary key&lt;/code&gt; as the profile’s primary and foreign key. This way the profile is dependent on the user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE Profiles
(
  UserID INTEGER NOT NULL PRIMARY KEY,
  Img VARCHAR(1),
  Bio TEXT,
  FOREIGN KEY (UserID) REFERENCES Users(ID)
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Insert data to the user and profile.
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO Users (Username, Password) VALUES 
  ('Ben', 'secret'),
  ('Jim', 'secret'),
  ('Luk', 'secret');

INSERT INTO Profiles (UserID, Img, BIO) VALUES
  (1, '😎', 'I am a cool guy'),
  (2, '🥳', 'I love party'),
  (3, '🤠', 'I am a cowboy');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  Query user and profile information using inner join.
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;We use Aliases to give the temporary names &lt;code&gt;u&lt;/code&gt; for Users and &lt;code&gt;p&lt;/code&gt; for Profiles.&lt;/li&gt;
&lt;li&gt;Use SELECT to choose what fields you want selected from the database.&lt;/li&gt;
&lt;li&gt;Join the Profiles with the Users where the ID's match.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT u.Username, p.Img, p.Bio
FROM Profiles p
JOIN Users u ON p.UserID = u.ID;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Result:&lt;br&gt;
Ben|😎|I am a cool guy&lt;br&gt;
Jim|🥳|I love party&lt;br&gt;
Luk|🤠|I am a cowboy&lt;/p&gt;

</description>
      <category>sql</category>
    </item>
    <item>
      <title>SQL Course: Get Started.</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Mon, 01 Jul 2024 13:27:30 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/sql-course-get-started-4ho6</link>
      <guid>https://dev.to/emanuelgustafzon/sql-course-get-started-4ho6</guid>
      <description>&lt;p&gt;Learn SQL in a funny way by building a social media database. The database will contain users, profiles, posts with likes and users will also be able to follow each other.&lt;/p&gt;

&lt;p&gt;I will reference to w3schools.com during this series so you can learn a bit more about the theory and this series will teach you how to put it into practice.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;I am using &lt;code&gt;SQLite&lt;/code&gt; for this course. If you use another database it’s fine but maybe the syntax will be slightly different. But w3schools gives examples of different syntax. &lt;/p&gt;

&lt;p&gt;I am also using &lt;code&gt;Replit&lt;/code&gt; for this tutorial as IDE. You can easily create an account and create a new Repl with the SQLite template. That makes it easy to set up and you can also code in your browser or on your phone or IPad so you can take this tutorial on the go. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://replit.com/" rel="noopener noreferrer"&gt;https://replit.com/&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What we will learn
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Creating Tables with primary and foreign keys. &lt;/li&gt;
&lt;li&gt;One to one relationships.&lt;/li&gt;
&lt;li&gt;One to many relationships.&lt;/li&gt;
&lt;li&gt;Many to many relationships.&lt;/li&gt;
&lt;li&gt;Query data.&lt;/li&gt;
&lt;li&gt;Inner joins, left joins and self joins and nested joins.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>sql</category>
      <category>learning</category>
      <category>join</category>
      <category>query</category>
    </item>
    <item>
      <title>C# pass delegate methods as arguments.</title>
      <dc:creator>Emanuel Gustafzon</dc:creator>
      <pubDate>Thu, 27 Jun 2024 09:55:02 +0000</pubDate>
      <link>https://dev.to/emanuelgustafzon/c-pass-delegate-methods-as-arguments-10ap</link>
      <guid>https://dev.to/emanuelgustafzon/c-pass-delegate-methods-as-arguments-10ap</guid>
      <description>&lt;p&gt;With delegates you can pass methods as argument a to other methods. &lt;/p&gt;

&lt;p&gt;The delegate object holds references to other methods and that reference can be passed as arguments. &lt;/p&gt;

&lt;p&gt;This is a key functionality when working within the functional programming paradigm. &lt;/p&gt;

&lt;p&gt;We can create callbacks by utilizing this technique.&lt;/p&gt;

&lt;p&gt;A function that receives one more multiple functions as argument or/and returns a function is called higher order functions. &lt;/p&gt;

&lt;p&gt;Below is an example of a Map function that receives a int array and a callback function. You can then customize the callback to modify each element in the array. The Map method returns a new array with each item modified.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Program {
    // define Callback delegate obj
    public delegate int Callback(int valueToModify);

    // Map function that takes a cb to modify each item in array and returns a new modified array
    public static int[] Map(int[] arr, Callback callback) {
    int[] newArr = new int[arr.Length];
    for (int i = 0; i &amp;lt; arr.Length; i++) {
        newArr[i] = callback(arr[i]);
        }

    return newArr;
    }

    public static void Main (string[] args) {
      // Create custom callback
      Callback squareNumbers = x =&amp;gt; x * x;
      int[] arr = {1, 2, 3, 4, 5};

      // pass the custom cb as arg
      int[] squaredArr = Map(arr, squareNumbers);

      foreach (int num in squaredArr)       {
          Console.WriteLine(num);
      }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can now play around with this a feel free to define your callback with a lambda function as we learned in the last chapter. &lt;/p&gt;

&lt;p&gt;Happy Coding!&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>delegate</category>
      <category>higherorderfunctions</category>
    </item>
  </channel>
</rss>
