上根據控制器上的屬性解決依賴關係我試圖儘可能輕鬆地在ASP.NET Core MVC
項目的數據訪問層中實現緩存。主要問題是我們不希望從所有頁面上的緩存中讀取,只有一部分。下面的例子應該說明了這種設置,我們有:如何在ASP.NET Core MVC
[UseCache]
public class ControllerA : Controller
{
public ControllerA(IBuilder builder)
{
// Should resolve an IBuilder with a CacheService
}
}
public class ControllerB : Controller
{
public ControllerB(IBuilder builder)
{
// Should resolve an IBuilder with a NullCacheService
}
}
public class Builder : IBuilder
{
public Builder(ICacheService cacheService)
{
// The type of the resolved ICacheService depends on the UseCache
// attribute on any of the object that depends on this IBuilder
}
}
public class CacheService : ICacheService
{
public Object Get(string key, Func<Object> getValue)
{
// Check if the value is cached against Key and return it if it's not
// Obviously needs a lot more here regarding caching timeframes, expiry etc
}
}
public class NullCacheService : ICacheService
{
public Object Get(string key, Func<Object> getValue)
{
// Don't do anything with key, just do the work in getValue and return it
}
}
public class UseCacheAttribute : Attribute
{
}
我知道Autofac can deal with resolving dependencies using attributes但
的Autofac.Extras.AttributeMetadata包未在ASP.NET MVC核心
- 支持
即使它受到支持,我也看不到它將如何支持包含此對象的對象的屬性檢測。
我很高興介紹一個新的IoC框架,我們並不依賴於Autofac或默認的IoC實現。
是我想要實現的可能嗎?什麼會被認爲是更好的緩存解決方案?
根據[Autofac.Extras.AttributeMetadata v4.0.1發行說明](https://github.com/autofac/Autofac.Extras.AttributeMetadata/releases/tag/v4.0.1),您可以使用Autofac.Features。 .net核心支持的AttributeFilters'。 – Sakis
@Sakis這是真的,但不允許你使用你自己的屬性,據我所知 - 這需要你註冊AttributedMetadataModule [在Autofac.Extras.AttributeMetadata中](https://autofac.org/apidoc /html/D6EFF2D8.htm),這不會被移植到.NET Core。 –