如何根据ASP.NET Core MVC中控制器上的属性解析依赖项

时间:2017-07-18 09:37:27

标签: c# dependency-injection 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 
{

}

我知道GetFileTime function但是

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

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

  3. 我很高兴推出新的IoC框架,我们不依赖于Autofac或默认的IoC实现。

    我努力实现的目标是什么?什么被认为是更好的缓存解决方案?

1 个答案:

答案 0 :(得分:1)

  

我很高兴推出一个新的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