Brezelmann
Brezelmann

Reputation: 389

Strategy Pattern with ASP.Net Core DI

While building my Rest API I stumbled across building a Cached Repository based on this Article.

Building a CachedRepository via Strategy Pattern

I liked the idea because the code seemed nice and dry. Therefore I went and gave it a shot and the Implementation was quite nice.

However now I want to wire up my DI (the Standard Microsoft DI coming with ASP.Net Core and nothing fancy) and I am Facing some trouble there.

Basically the problem is that I have multiple implementation of the same interface and the cached implementation takes a reference to the direct implementation like so:

public class CachedArticleRepository : IArticleRepository
{
    public CachedArticleRepository(IArticleRepository article, IMemoryCache cache)
    {
        _article = article;
        _cache = cache;
    }
}

public class ArticleRepository : IArticleRepository
{
    public ArticleRepository(IAmbientContextLocator locator)
    {
        _locator = locator;
    }    
}

I use it in my service (as explained by the Article) like this:

public class DivisionService : IDivisionService
{
    public DivisionService(IArticleRepository article)
    {
        _article = article;
    }
}

My Question is now how can I configure the DI so that the Non Cached Variant is used for building the Cached Repository and the Cached Repository is used for everything else?

Upvotes: 4

Views: 4053

Answers (1)

Nkosi
Nkosi

Reputation: 247153

Use the factory delegate overload when registering the service

//...

services.AddScoped<ArticleRepository>();
services.AddScoped<IArticleRepository, CachedArticleRepository>(serviceProvider => {
    IArticleRepository nonCachedVarient = serviceProvider.GetService<ArticleRepository>();
    IMemoryCache cache = serviceProvider.GetService<IMemoryCache>();
    return new CachedArticleRepository (nonCachedVarient, cache);
});

//...

That way the Non Cached Variant is used for building the Cached Repository and the Cached Repository is used for everything else.

The above code assumes all other dependencies are added to the service collection.

The CachedArticleRepository is registered as IArticleRepository so it will be resolved whenever that dependency is needed.

You can change the service life time to suit your needs. AddScoped was used just to demonstrate the registration process.

Upvotes: 4

Related Questions