如何根据核心 MVC 中控制器上的属性解析依赖关系 ASP.NET



我正在尝试在 ASP.NET 核心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可以使用属性处理解决依赖关系,但是

  1. Autofac.Extras.AttributeMetadata 包在 Core MVC ASP.NET 不受支持

  2. 即使它被支持,我也看不出它如何支持对包含此对象的属性检测。

我很高兴介绍一个新的 IoC 框架,我们不受 Autofac 或默认 IoC 实现的约束。

我想要实现的目标可能吗?什么被认为是更好的缓存解决方案?

我很高兴

介绍一个新的 IoC 框架,我们不依赖于 Autofac 或默认的 IoC 实现。

我对Autofac不是很熟悉,但我熟悉Simple Injector,所以我可以向您展示如何使用Simple Injector应用此类注册:

var cache = new CacheService();
container.RegisterConditional(typeof(IBuilder),
Lifestyle.Transient.CreateRegistration<Builder>(
() => new Builder(cache),
container),
c => c.Consumer.ImplementationType.GetCustomAttribute<UseCacheAttribute>() != null);
container.RegisterConditional(typeof(IBuilder),
Lifestyle.Transient.CreateRegistration<Builder>(
() => new Builder(new NullCacheService()), 
container),
c => !c.Handled);

此注册有点复杂,因为您希望根据Builder的使用者更改Builder类型的依赖项。查找消费者的消费者的"链"是Simple Injector不支持的,因为它很容易导致不正确的行为,特别是当中间消费者的生活方式不是短暂的时。这是有条件的注册是针对IBuilder而不是ICacheService的。

最新更新