<?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[Stories by Fatih Mert on Medium]]></title>
        <description><![CDATA[Stories by Fatih Mert on Medium]]></description>
        <link>https://medium.com/@fatihmert93?source=rss-b583b4919637------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*M63f1QQazHYOTzkG.jpg</url>
            <title>Stories by Fatih Mert on Medium</title>
            <link>https://medium.com/@fatihmert93?source=rss-b583b4919637------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:41:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fatihmert93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[.Net Core Dapper ile Connection Factory Tasarımı (Design Patterns)]]></title>
            <link>https://medium.com/@fatihmert93/net-core-dapper-ile-connection-factory-tasar%C4%B1m%C4%B1-design-patterns-8ecc252beb48?source=rss-b583b4919637------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ecc252beb48</guid>
            <category><![CDATA[connection-pool]]></category>
            <category><![CDATA[dapper]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Fatih Mert]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 21:14:38 GMT</pubDate>
            <atom:updated>2020-08-27T15:17:55.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bU1r9sdVPZsPJww3YlFNwg.png" /></figure><h3>Dapper kütüphanesi ile .Net Core’da Connection Factory Tasarımı (Design Patterns)</h3><p>Herkese merhaba, öncelikle dapper kullananlar bilir dapper kullanırken IDbConnection interface’i üzerinden bir connection açmanız gerekmektedir. Bu interface’i kullanmak içinde kullanacağınız database’e ait bir provider üzerinden obje yaratıp IDbConnection a newlemeniz gerekmektedir.</p><p>Çoğunlukla şu şekilde bir kullanımını yaparlar</p><pre>using(IDbConnection conn = new SqlConnection())</pre><pre>{</pre><pre>   conn.Open();</pre><pre>   Type type = conn.Query&lt;Type&gt;(“SELECT * FROM TABLE_NAME”)</pre><pre>   conn.Close();</pre><pre>}</pre><p>Ancak bu solid açısından oldukça yanlış bir kullanımdır.</p><p>Hem aynı using block larını her sorguda tekrarlamak zorunda kalırsınız, hem her sorguda connection open ve connection close işlemlerini tekrarlarsınız hem de MsSql bağımlı bir kodunuz olmuş olur.</p><h4>Bunun yerine ne yapabiliriz?</h4><p>Ben burada connection oluşturma işine bir factory ye vermeyi tercih ederim.</p><pre>public interface IConnectionFactory : IDisposable<br>{<br>    IDbConnection Connection { get; }<br>}</pre><p>Yukarıdaki gibi bir Factory interface imiz olsa ve bu bir IDisposable obje olsa. Şimdi bize bir Base Factory class gerekiyor</p><pre>public abstract class ConnectionFactoryBase : IConnectionFactory<br>{<br>    private string _connectionString;<br><br>    protected abstract DbProviderFactory GetProviderFactory();<br><br>    protected ConnectionFactoryBase(string connectionString)<br>    {<br>        _connectionString = connectionString;<br>    }<br><br>    protected virtual string GetConnectionString()<br>    {<br>        return _connectionString;<br>    }<br><br>    public void SetConnectionString(string connectionString)<br>    {<br>        this._connectionString = connectionString;<br>    }<br><br><br>    public IDbConnection Connection<br>    {<br>        get<br>        {<br>            var factory = GetProviderFactory();<br>            var connection = factory.CreateConnection();<br>            if (connection == null) throw new Exception(&quot;There is available connection factory!&quot;);<br>            connection.ConnectionString = GetConnectionString();<br>            if(connection.State != ConnectionState.Open)<br>                connection.Open();<br>            return connection;<br>        }<br>    }<br><br>    #region IDisposable Support<br>    private bool _disposedValue = false; // To detect redundant calls<br><br>    protected virtual void Dispose(bool disposing)<br>    {<br>        if (_disposedValue) return;<br>        if (disposing)<br>        {<br>            // TODO: dispose managed state (managed objects).<br>            Connection.Close();<br>        }<br><br>        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.<br>        // TODO: set large fields to null.<br><br>        _disposedValue = true;<br>    }<br><br><br>    <br>    public void Dispose()<br>    {<br>        <br>        Dispose(true);<br>        <br>        // GC.SuppressFinalize(this);<br>    }<br>    #endregion<br>}</pre><p>Yukarıdaki abstract kodda bu class tan kendi classını türeten kişi</p><pre>protected abstract DbProviderFactory GetProviderFactory();</pre><p>buradaki abstract methodun içinde doldurarak hangi database in provider ını kullanacağını kendisi belirleyebilecek. Ayrıca Connection talep edildiğinde burada belirlenen provider a göre bir connection yapılıp open edildikten sonra IDbConnection tipinde bir obje döner. Classımız IDisposable yapıda olduğu için obje Dispose edildiği sırada Connection da kapatılır.</p><p>Aşağıda MsSql için abstract classımızdan türettiğimiz yeni bir class tasarımını gösterelim.</p><pre>public class SqlConnectionFactory : ConnectionFactoryBase<br>{<br>    protected override DbProviderFactory GetProviderFactory()<br>    {<br>        var factory =      DbProviderFactories.GetDbProviderFactory(DataAccessProviderTypes.SqlServer);<br>        return factory;<br>    }<br><br>    public SqlConnectionFactory(string connectionString) : base(connectionString)<br>    {<br>    }<br>}</pre><p>Şimdi DbProviderFactory ne iş yapar onu anlatalım.</p><pre>public enum DataAccessProviderTypes<br>{<br>    SqlServer,<br>    SqLite,<br>    MySql,<br>    PostgreSql<br>}<br><br>public class DbProviderFactories<br>{<br>    private static DbProviderFactory GetDbProviderFactory(string dbProviderFactoryTypeName, string assemblyName)<br>    {<br>        var instance = ReflectionUtils.GetStaticProperty(dbProviderFactoryTypeName, &quot;Instance&quot;);<br>        if (instance == null)<br>        {<br>            var a = ReflectionUtils.LoadAssembly(assemblyName);<br>            if (a != null)<br>                instance = ReflectionUtils.GetStaticProperty(dbProviderFactoryTypeName, &quot;Instance&quot;);<br>        }<br><br>        if (instance == null)<br>            throw new InvalidOperationException(string.Format(&quot;UnableToRetrieveDbProviderFactoryForm&quot;, dbProviderFactoryTypeName));<br><br>        return instance as DbProviderFactory;<br>    }<br><br><br>    public static DbProviderFactory GetDbProviderFactory(DataAccessProviderTypes type)<br>    {<br>        switch (type)<br>        {<br>            case DataAccessProviderTypes.SqlServer:<br>                return SqlClientFactory.Instance;<br>            case DataAccessProviderTypes.SqLite:<br>                return GetDbProviderFactory(&quot;Microsoft.Data.Sqlite.SqliteFactory&quot;, &quot;Microsoft.Data.Sqlite&quot;);<br>            case DataAccessProviderTypes.MySql:<br>                return GetDbProviderFactory(&quot;MySql.Data.MySqlClient.MySqlClientFactory&quot;, &quot;MySql.Data&quot;);<br>            case DataAccessProviderTypes.PostgreSql:<br>                return GetDbProviderFactory(&quot;Npgsql.NpgsqlFactory&quot;, &quot;Npgsql&quot;);<br>            default:<br>                throw new NotSupportedException(&quot;Unsupported_Provider&quot;);<br>        }<br>    }<br><br>    public static DbProviderFactory GetDbProviderFactory(string providerName)<br>    {<br>        var providername = providerName.ToLower();<br><br>        if (providerName == &quot;system.data.sqlclient&quot;)<br>            return GetDbProviderFactory(DataAccessProviderTypes.SqlServer);<br>        if (providerName == &quot;system.data.sqlite&quot; || providerName == &quot;microsoft.data.sqlite&quot;)<br>            return GetDbProviderFactory(DataAccessProviderTypes.SqLite);<br>        if (providerName == &quot;mysql.data.mysqlclient&quot; || providername == &quot;mysql.data&quot;)<br>            return GetDbProviderFactory(DataAccessProviderTypes.MySql);<br>        if (providerName == &quot;npgsql&quot;)<br>            return GetDbProviderFactory(DataAccessProviderTypes.PostgreSql);<br><br>        throw new NotSupportedException(string.Format(&quot;Unsupported_Provider&quot;, providerName));<br>    }<br><br><br>}</pre><p>Dışarıdan oluşturulmasını istediğimiz database eğit Provider ı belirtiğim enum veya Type cinsinden parametreyle Reflection yardımcıyla objeyi dinamik olarak invoke ederek bize döner.</p><p>Daha sonra tek yapmanız gereken projenizdeki dependency injection yapısına interface ve class larınızı register etmek.</p><pre>services.AddScoped&lt;IConnectionFactory&gt;(serviceProvider =&gt;<br>{<br>    var connectionString = configuration.GetSqlConnection(&quot;ConnectionString&quot;);<br>    return new SqlConnectionFactory(connectionString);<br>});<br><br>services.AddScoped(typeof(DapperGenericRepository&lt;&gt;),typeof(SqlGenericRepository&lt;&gt;));<br></pre><p>İşlemlerimiz bu kadar şimdi istediğiniz class içierisinde bir IDbConnectionFactory yi constructor da inject ederek kullanabilirsiniz.</p><p>Örnek bir kullanım şu şekilde olmalıdır.</p><pre>public abstract class DapperGenericRepository&lt;TEntity&gt; where TEntity : class, new()<br>{<br>    private readonly IConnectionFactory _connectionFactory;<br>    protected readonly IDbConnection Connection;<br>    private readonly string _tableName;<br>    private IDbTransaction _dbTransaction;<br><br><br>    protected DapperGenericRepository(IConnectionFactory connectionFactory)<br>    {<br>        _connectionFactory = connectionFactory;<br>        Connection = _connectionFactory.Connection;<br>    }<br>}</pre><p>İyi çalışmalar dilerim. Umarım faydalanabileceğiniz bir içerik olmuştur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ecc252beb48" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>