【问题标题】:Constructor not being called in class类中未调用构造函数
【发布时间】:2019-01-14 23:23:44
【问题描述】:

我正在 .net core 2.2 中创建一个助手,用于缓存到 Redis。当我调用 Add 方法时,它不会通过我的构造函数来创建 IDistributedCache 实例。

public class Cache
{
    public static IDistributedCache _cache;
    public Cache(IDistributedCache cache)
    {
        _cache = cache;
    }
    public static void Add(string key, byte[] value, int expiration)
    {
        var options = new DistributedCacheEntryOptions()
            .SetSlidingExpiration(TimeSpan.FromSeconds(expiration));
        _cache.Set(key, value, options);
    }
}

我不完全理解我错过了什么。我这样称呼方法

Cache.Add("time", encodedCurrentTimeUTC, expiration);

编辑: 我已经删除了静态条目

public class Cache
{
    public IDistributedCache _cache;
    public Cache(IDistributedCache cache)
    {
        _cache = cache;
    }
    public void Add(string key, byte[] value, int expiration)
    {
        var options = new DistributedCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(expiration));
        _cache.Set(key, value, options);
    }
}

但是当我尝试调用该方法时

var newItem = new Cache();
newItem.Add("time", encodedCurrentTimeUTC, expiration);

它告诉我我没有将参数传递给缓存构造函数。

【问题讨论】:

  • 你的 Add 方法是静态的,所以我认为你的构造函数不会被调用。
  • 你没有打电话给new Cache
  • @User 问题是静态构造函数不能包含参数 - 它们从哪里来?
  • @User 你确定静态构造函数是合适的吗?应该经常避免使用静态类。最好使用该类的单个实例,然后向 IoC 容器注册单个实例。
  • @User 好吧,如果您要提出解决问题的方法,最好先考虑一下。如果您不确定这是一个好主意,请让其他人提供帮助。

标签: c# asp.net-core


【解决方案1】:

由于您使用的是 DI,请完全避免使用 new。 让您的班级Cache 实现一个接口,例如:

public interface ICache
{
    void Add(string key, byte[] value, int expiration);
}

public class Cache : ICache
{
    public IDistributedCache _cache;
    public Cache(IDistributedCache cache)
    {
        _cache = cache;
    }
    public void Add(string key, byte[] value, int expiration)
    {
        var options = new DistributedCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(expiration));
        _cache.Set(key, value, options);
    }
}

在您的容器中注册CacheICacheAutoFac 例子:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Cache>().As<ICache>();

然后在需要使用Cache 对象的类中,将其作为依赖项注入:

class ClassThatNeedsACache
{
    ICache _cache;
    ClassThatNeedsACache(ICache cache)
    {
        _cache = cache;
    }

    void MethodThatUsesACache()
    {
        // Some other code to create your encodedCurrentTimeUTC and expiration
        _cache.Add("time", encodedCurrentTimeUTC, expiration);
    }
}

依赖注入框架将你的组合根中的所有东西连接在一起,例如ASP.NET 中的 Global.asax,并维护应用程序中对象的创建和生命周期。

【讨论】:

  • @TheDizzle “完全避免使用new”是很好的建议。 This video 深入探讨了为什么这是个好主意。
  • 完美解决方案+1
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2018-07-21
  • 2018-02-28
  • 2018-03-31
相关资源
最近更新 更多