Dan Bailiff
Dan Bailiff

Reputation: 1571

Using Entity Framework and Transient Fault Handling Block WITHOUT Azure

I have several apps that rely on a repository using EF 4. Sometimes, a SQL operation will fail just because (i.e. timeout, failed connection, etc.).

I want to use the Transient Fault Handling Application Block, but I am NOT using Azure. There seems to be a proliferation of info out there for Azure scenarios, but no info on using a "barebones" approach. I worry that if I use the Azure detection strategies, it just won't work.

Anyone know where I can find info on how to best use this?

Upvotes: 4

Views: 1974

Answers (1)

Dan Bailiff
Dan Bailiff

Reputation: 1571

I was able to get started by looking here: http://hmadrigal.wordpress.com/2012/04/23/automatic-retries-using-the-transient-fault-handling-from-enterprise-libraries-entlib/

You just have to write your own detection strategy class. In my case it looks like this:

public class EntityFrameworkTransientErrorDetectionStrategy : ITransientErrorDetectionStrategy
{
    #region ITransientErrorDetectionStrategy Members

    public bool IsTransient(Exception ex)
    {
        if (ex is SqlException)
        {
            return true;
        }
        else
            return false;
    }

    #endregion
}

In my repository constructor I have this:

_retryStrategy = new FixedInterval(_retryLimit, new TimeSpan(0, 0, 0, 0, 500));
        _retryPolicy = new RetryPolicy<EntityFrameworkTransientErrorDetectionStrategy>(_retryStrategy);     // use our custom detection strategy

        _retryPolicy.Retrying += (sender, args) =>
            {
                // Log any retries as warnings
                _logger.WarnFormat("Retry {0} of {1} due to exception: {2}", args.CurrentRetryCount, _retryLimit, args.LastException);
            };

A typical repository method:

public override HarvesterDomain.Source SelectSource(Guid id)
    {
        HarvesterDomain.Source source = null;
        _retryPolicy.ExecuteAction(() =>
            {
                var contextSource = _context.Sources.Where(s => s.Id == id).FirstOrDefault();

                if (contextSource != null)
                    source = contextSource.ToHarvesterDomainSource();
            });
        return source;
    }

Upvotes: 2

Related Questions