简体   繁体   English

ASP.Net核心DI的战略模式

[英]Strategy Pattern with ASP.Net Core DI

While building my Rest API I stumbled across building a Cached Repository based on this Article . 在构建我的Rest API时,我偶然发现了基于这篇文章构建一个Cached Repository。

Building a CachedRepository via Strategy Pattern 通过策略模式构建CachedRepository

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. 但是现在我想连接我的DI(标准的Microsoft DI与ASP.Net Core一起推出并没什么特别的),我在那里面临一些麻烦。

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? 我现在的问题是如何配置DI以便非缓存变量用于构建缓存存储库,而缓存存储库用于其他所有内容?

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. 这样,Non Cached Variant用于构建Cached Repository,Cached Repository用于其他所有内容。

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. CachedArticleRepository注册为IArticleRepository因此只要需要该依赖项,就会解析它。

You can change the service life time to suit your needs. 您可以根据需要更改使用寿命。 AddScoped was used just to demonstrate the registration process. AddScoped仅用于演示注册过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM